formatting changes

formatting changes

--- datalogger.ino
+++ datalogger.ino
@@ -3,11 +3,10 @@
 #include <SD.h>
 #include <Wire.h>

-byte mac[] = {
-  0x98, 0x4F, 0xEE, 0x01, 0x5B, 0x00 };    // mac adress of galileo
-IPAddress ip(10,2,95,6);                    // ip of galileo
-unsigned int localPort = 5810;              // local port to listen on
-char packetBuffer[UDP_TX_PACKET_MAX_SIZE];  // buffer to hold incoming packet,
+byte mac[] = {0x98, 0x4F, 0xEE, 0x01, 0x5B, 0x00};  // mac adress of galileo
+IPAddress ip(10,2,95,6);                            // ip address of galileo
+unsigned int localPort = 5810;                      // local port to listen on
+char packetBuffer[UDP_TX_PACKET_MAX_SIZE];          // buffer to hold incoming packet,
 EthernetUDP Udp;

 const int DS1307 = 0x68;
@@ -37,25 +36,33 @@
 // --------------------------------------------------
 //   get the match number and increment
 // --------------------------------------------------
-int getMatchNum(void) {
+int getMatchNum(void)
+{
   File matchFile;
   char matchNumFile[] = "matchNum.txt";
   int match = 0;

-  if (!SD.exists(matchNumFile)) {
+  if (!SD.exists(matchNumFile))
+  {
     matchFile = SD.open(matchNumFile, FILE_WRITE);
-    if (matchFile) {
+    if (matchFile)
+    {
       matchFile.print(++match);
       matchFile.close();
     }
     else
+    {
       return (0);
+    }
   }
-  else {
+  else
+  {
     matchFile = SD.open(matchNumFile, FILE_READ);
-    if (matchFile) {
+    if (matchFile)
+    {
       char fileData = matchFile.read();
-      while (fileData != -1) {
+      while (fileData != -1)
+      {
         match = match*10 + (fileData - '0');
         fileData = matchFile.read();
       }
@@ -68,7 +75,9 @@
       matchFile.close();
     }
     else
+    {
       return (0);
+    }
   }
   return (match);
 }  // getMatchNum
@@ -77,8 +86,10 @@
 // --------------------------------------------------
 //   blink error lights
 // --------------------------------------------------
-void error() {
-  while(1) {
+void error()
+{
+  while(1)
+  {
     digitalWrite(redPin, LOW);
     delay(shortOff);
     digitalWrite(redPin, HIGH);
@@ -90,7 +101,8 @@
 // --------------------------------------------------
 //   setup function
 // --------------------------------------------------
-void setup() {
+void setup()
+{
   int match;

   system("telnetd -l /bin/sh");   // open galileo for ethernet access
@@ -124,7 +136,8 @@
 // --------------------------------------------------
 //   create data file and write headers
 // --------------------------------------------------
-int createDataFile(void) {
+int createDataFile(void)
+{
   //if (!(match = getMatchNum())) error();
   //sprintf(dataFileName, "%08d.csv", match);  // no clock
   readTime();
@@ -142,7 +155,8 @@
 // --------------------------------------------------
 //   main loop
 // --------------------------------------------------
-void loop() {
+void loop()
+{
   static int s = 0;
   static int ledState = 0;
   static unsigned long initialTime;
@@ -152,171 +166,211 @@
   static unsigned long redTime = 0;
   int packetSize;
   int i;
-  static int adc[6] = {
-    0,0,0,0,0,0  };
+  static int adc[6] = {0,0,0,0,0,0};
   static char chan = 0;
   float temp;
   static unsigned long muxTime = 0;
   char tempString[40];

-  switch(s) {
-
-  case 0:   //wait for first packet
-    packetSize = Udp.parsePacket();
-    if (packetSize) {
-      if (!createDataFile()) {
+  switch(s)
+  {
+
+    case 0:   //wait for first packet
+      packetSize = Udp.parsePacket();
+      if (packetSize)
+      {
+        if (!createDataFile())
+        {
+          i = Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
+          initialTime = millis();
+          packetTime = initialTime;
+          writeTime = 0;
+          if (packetBuffer[0] != '#')
+          {
+            dataFile.print(";\r\n");
+            dataFile.print(writeTime);
+            sprintf(tempString, ";%d;%d;%d;%d;%d;%d;", adc[0], adc[1], adc[2], adc[3], adc[4], adc[5]);
+            dataFile.print(tempString);
+          }
+          else
+          {
+            dataFile.print(";");
+          }
+          dataFile.write((uint8_t *)packetBuffer, i);
+          dataFile.flush();
+          redTime = initialTime + errorFlash;
+          digitalWrite(redPin, HIGH);
+          digitalWrite(redPin2, HIGH);
+          s = 1;
+        }
+        else
+        {
+          s = 7;
+        }
+      } // if
+      break;
+
+    case 1:   // wait for packet
+      packetSize = Udp.parsePacket();
+      if (packetSize)
+      {
         i = Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
-        initialTime = millis();
-        packetTime = initialTime;
-        writeTime = 0;
-        if (packetBuffer[0] != '#') {
+        packetTime = millis();
+        writeTime = packetTime - initialTime;
+        if (packetBuffer[0] != '#')
+        {
           dataFile.print(";\r\n");
           dataFile.print(writeTime);
           sprintf(tempString, ";%d;%d;%d;%d;%d;%d;", adc[0], adc[1], adc[2], adc[3], adc[4], adc[5]);
           dataFile.print(tempString);
         }
         else
+        {
           dataFile.print(";");
+        }
         dataFile.write((uint8_t *)packetBuffer, i);
         dataFile.flush();
-        redTime = initialTime + errorFlash;
+        redTime = packetTime + errorFlash;
         digitalWrite(redPin, HIGH);
         digitalWrite(redPin2, HIGH);
-        s = 1;
-      }
-      else
-        s = 7;
-    } // if
-    break;
-
-  case 1:   // wait for packet
-    packetSize = Udp.parsePacket();
-    if (packetSize) {
-      i = Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
-      packetTime = millis();
-      writeTime = packetTime - initialTime;
-      if (packetBuffer[0] != '#') {
-        dataFile.print(";\r\n");
-        dataFile.print(writeTime);
-        sprintf(tempString, ";%d;%d;%d;%d;%d;%d;", adc[0], adc[1], adc[2], adc[3], adc[4], adc[5]);
-        dataFile.print(tempString);
-      }
-      else
-        dataFile.print(";");
-      dataFile.write((uint8_t *)packetBuffer, i);
-      dataFile.flush();
-      redTime = packetTime + errorFlash;
-      digitalWrite(redPin, HIGH);
-      digitalWrite(redPin2, HIGH);
-    }
-    if ((millis() - packetTime) > timeOut)
-      s = 3;
-    break;
-
-  case 3:  // close
-    dataFile.print("\r\n");
-    dataFile.close();
-    s = 0;
-    break;
-
-  case 7:   // error
-    break;
+      }
+      if ((millis() - packetTime) > timeOut)
+      {
+        s = 3;
+      }
+      break;
+
+    case 3:  // close
+      dataFile.print("\r\n");
+      dataFile.close();
+      s = 0;
+      break;
+
+    case 7:   // error
+      break;

   }  // switch s

   //led state machine

-  switch(ledState) {
-  case 0:
-    if (millis() > redTime) {
-      digitalWrite(redPin, LOW);
-      digitalWrite(redPin2, LOW);
-    }
-    if ( millis() > grnTime) {
-      digitalWrite(grnPin, HIGH);
-      digitalWrite(grnPin2, HIGH);
-      grnTime = millis() + shortOn;
-      ledState = 1;
-    }
-    break;
-
-  case 1:
-    if (millis() > redTime) {
-      digitalWrite(redPin, LOW);
-      digitalWrite(redPin2, LOW);
-    }
-    if (millis() > grnTime) {
-      digitalWrite(grnPin, LOW);
-      digitalWrite(grnPin2, LOW);
-      grnTime = millis() + shortOff;
-      if (s == 0)
+  switch(ledState)
+  {
+    case 0:
+      if (millis() > redTime)
+      {
+        digitalWrite(redPin, LOW);
+        digitalWrite(redPin2, LOW);
+      }
+      if ( millis() > grnTime)
+      {
+        digitalWrite(grnPin, HIGH);
+        digitalWrite(grnPin2, HIGH);
+        grnTime = millis() + shortOn;
+        ledState = 1;
+      }
+      break;
+
+    case 1:
+      if (millis() > redTime)
+      {
+        digitalWrite(redPin, LOW);
+        digitalWrite(redPin2, LOW);
+      }
+      if (millis() > grnTime)
+      {
+        digitalWrite(grnPin, LOW);
+        digitalWrite(grnPin2, LOW);
+        grnTime = millis() + shortOff;
+        if (s == 0)
+        {
+          ledState = 3;
+        }
+        else
+        {
+          ledState = 2;
+        }
+      }
+      break;
+
+    case 2:
+      if (millis() > redTime)
+      {
+        digitalWrite(redPin, LOW);
+        digitalWrite(redPin2, LOW);
+      }
+      if ( millis() > grnTime)
+      {
+        digitalWrite(grnPin, HIGH);
+        digitalWrite(grnPin2, HIGH);
+        grnTime = millis() + shortOn;
         ledState = 3;
-      else
-        ledState = 2;
-    }
-    break;
-
-  case 2:
-    if (millis() > redTime) {
-      digitalWrite(redPin, LOW);
-      digitalWrite(redPin2, LOW);
-    }
-    if ( millis() > grnTime) {
-      digitalWrite(grnPin, HIGH);
-      digitalWrite(grnPin2, HIGH);
-      grnTime = millis() + shortOn;
-      ledState = 3;
-    }
-    break;
-
-  case 3:
-    if (millis() > redTime) {
-      digitalWrite(redPin, LOW);
-      digitalWrite(redPin2, LOW);
-    }
-    if (millis() > grnTime) {
-      digitalWrite(grnPin, LOW);
-      digitalWrite(grnPin2, LOW);
-      grnTime = millis() + longOff;
-      if (s == 7)
-        ledState = 4;
-      else
-        ledState = 0;
-    }
-    break;
-
-  case 4:
-    if (millis() > grnTime) {
-      grnTime = millis() + shortOff;
-      digitalWrite(grnPin, HIGH);
-      digitalWrite(grnPin2, HIGH);
-      digitalWrite(redPin, LOW);
-      digitalWrite(redPin2, LOW);
-      ledState = 5;
-    }
-    break;
-
-  case 5:
-    if (millis() > grnTime) {
-      grnTime = millis() + shortOff;
-      digitalWrite(grnPin, LOW);
-      digitalWrite(grnPin2, LOW);
-      digitalWrite(redPin, HIGH);
-      digitalWrite(redPin2, HIGH);
-      if (s == 7)
-        ledState = 4;
-      else
-        ledState = 3;
-    }
-    break;
-  }  // led switch
-
-  if (millis() > muxTime) {
+      }
+      break;
+
+    case 3:
+      if (millis() > redTime)
+      {
+        digitalWrite(redPin, LOW);
+        digitalWrite(redPin2, LOW);
+      }
+      if (millis() > grnTime)
+      {
+        digitalWrite(grnPin, LOW);
+        digitalWrite(grnPin2, LOW);
+        grnTime = millis() + longOff;
+        if (s == 7)
+        {
+          ledState = 4;
+        }
+        else
+        {
+          ledState = 0;
+        }
+      }
+      break;
+
+    case 4:
+      if (millis() > grnTime)
+      {
+        grnTime = millis() + shortOff;
+        digitalWrite(grnPin, HIGH);
+        digitalWrite(grnPin2, HIGH);
+        digitalWrite(redPin, LOW);
+        digitalWrite(redPin2, LOW);
+        ledState = 5;
+      }
+      break;
+
+    case 5:
+      if (millis() > grnTime)
+      {
+        grnTime = millis() + shortOff;
+        digitalWrite(grnPin, LOW);
+        digitalWrite(grnPin2, LOW);
+        digitalWrite(redPin, HIGH);
+        digitalWrite(redPin2, HIGH);
+        if (s == 7)
+        {
+          ledState = 4;
+        }
+        else
+        {
+          ledState = 3;
+        }
+      }
+      break;
+    }  // led switch
+
+  if (millis() > muxTime)
+  {
     temp = (float)analogRead(0) * 0.488;
     adc[chan] = (int)temp;
     //Serial.println(adc[chan]);
-    if (++chan > 5) chan = 0;
+    if (++chan > 5)
+    {
+      chan = 0;
+    }
     mux(chan);
     muxTime = millis() + 50;
   }
@@ -327,62 +381,69 @@
 // --------------------------------------------------
 //   switch the mux channels
 // --------------------------------------------------
-void mux(char chan) {
-  switch(chan) {
-  case 0:   // sensor 0
-    digitalWrite(a0Pin, LOW);
-    digitalWrite(a1Pin, LOW);
-    digitalWrite(a2Pin, LOW);
-    break;
-
-  case 1:   // sensor 1
-    digitalWrite(a0Pin, HIGH);
-    digitalWrite(a1Pin, LOW);
-    digitalWrite(a2Pin, LOW);
-    break;
-
-  case 2:   // sensor 2
-    digitalWrite(a0Pin, LOW);
-    digitalWrite(a1Pin, HIGH);
-    digitalWrite(a2Pin, LOW);
-    break;
-
-  case 3:   // sensor 3
-    digitalWrite(a0Pin, HIGH);
-    digitalWrite(a1Pin, HIGH);
-    digitalWrite(a2Pin, LOW);
-    break;
-
-  case 4:   // sensor 4
-    digitalWrite(a0Pin, LOW);
-    digitalWrite(a1Pin, LOW);
-    digitalWrite(a2Pin, HIGH);
-    break;
+void mux(char chan)
+{
+  switch(chan)
+  {
+    case 0:   // sensor 0
+      digitalWrite(a0Pin, LOW);
+      digitalWrite(a1Pin, LOW);
+      digitalWrite(a2Pin, LOW);
+      break;
+
+    case 1:   // sensor 1
+      digitalWrite(a0Pin, HIGH);
+      digitalWrite(a1Pin, LOW);
+      digitalWrite(a2Pin, LOW);
+      break;
+
+    case 2:   // sensor 2
+      digitalWrite(a0Pin, LOW);
+      digitalWrite(a1Pin, HIGH);
+      digitalWrite(a2Pin, LOW);
+      break;
+
+    case 3:   // sensor 3
+      digitalWrite(a0Pin, HIGH);
+      digitalWrite(a1Pin, HIGH);
+      digitalWrite(a2Pin, LOW);
+      break;
+
+    case 4:   // sensor 4
+      digitalWrite(a0Pin, LOW);
+      digitalWrite(a1Pin, LOW);
+      digitalWrite(a2Pin, HIGH);
+      break;
+
+    case 5:
+      digitalWrite(a0Pin, HIGH);
+      digitalWrite(a1Pin, LOW);
+      digitalWrite(a2Pin, HIGH);
+      break;

-  case 5:
-    digitalWrite(a0Pin, HIGH);
-    digitalWrite(a1Pin, LOW);
-    digitalWrite(a2Pin, HIGH);
-    break;
-  }
-
-}
+  } // switch
+
+} // mux

 // --------------------------------------------------
 //   convert byte to decimal
 // --------------------------------------------------
-byte bcdToDec(byte val) {
+byte bcdToDec(byte val)
+{
   return ((val / 16 * 10) + (val % 16));
-}
+
+} // bcdToDec

 // --------------------------------------------------
 //   print the time from the RTC
 // --------------------------------------------------
-void printTime() {
+void printTime()
+{
   char buffer[3];
   const char* AMPM = 0;
+
   readTime();
   Serial.print("20");
   Serial.print(year);
@@ -392,7 +453,8 @@
   Serial.print(day);

   Serial.print(" ");
-  if (hour > 12) {
+  if (hour > 12)
+  {
     hour -= 12;
     AMPM = " PM";
   }
@@ -402,13 +464,15 @@
   sprintf(buffer, "%02d", minute);
   Serial.print(buffer);
   Serial.println(AMPM);
-}
+
+} // printTime

 // --------------------------------------------------
 //   read the time from the RTC
 // --------------------------------------------------
-void readTime() {
+void readTime()
+{
   Wire.beginTransmission(DS1307);
   Wire.write(byte(0));
   Wire.endTransmission();
@@ -421,5 +485,5 @@
   month = bcdToDec(Wire.read());
   year = bcdToDec(Wire.read());

-}
-
+} // readTime
+


Cleaned up firmware logic

Cleaned up firmware logic

--- Firmware/Digispark_Firmware_Rev1.0/Digispark_Firmware_Rev1.0.ino
+++ Firmware/Digispark_Firmware_Rev1.0/Digispark_Firmware_Rev1.0.ino
@@ -1,10 +1,10 @@
 //Name pins
+//INPUTS
 const int THERMISTOR = 1; //For analogRead, pin2 is 1. Yes, confusing...
 const int BIASPOT = 3; //For analogRead, pin3 is 3
-//CHANGED LED PIN
-//const int LED = 4; //LED on pin 4
-const int LED = 1; //internal LED on pin 1
-
+//OUTPUTS
+const int LED = 4; //Circuit LED on pin 4
+//const int LED = 1; //internal LED on pin 1
 const int RLY_OUT = 5; //Output, pin no. matches

@@ -19,63 +19,55 @@
   digitalWrite(RLY_OUT, LOW);

   //Blink Led SOS to display reset. Don't blink on output transistor.
-  initBlink(100, 100, 3); //s
-  initBlink(250, 250, 3); //o
-  initBlink(100, 100, 3); //s
+  initBlink(LED, 75, 75, 3); //s
+  delay(50);
+  initBlink(LED, 150, 150, 3); //o
+  delay(50);
+  initBlink(LED, 75, 75, 3); //s
 }

 // the loop routine runs over and over again forever:
 void loop() {
   //Read sensor and bias pots
   //float temp = analogRead(THERMISTOR); //Use a float if doing math to correct for non-linear sensor
+  int bias = readAvg(3, BIASPOT, 30); //3 averages of the bias pot
+  int temp = readAvg(5, THERMISTOR, 250); //5 averages of the thermistor, .25sec total averaging time.

-  //int temp = analogRead(THERMISTOR);
-  //int bias = analogRead(BIASPOT);
-  int bias = readAvg(3, BIASPOT); //5 averages of the bias pot
-  int temp = readAvg(5, THERMISTOR); //5 averages of the thermistor
-
-  //Control logic
-/*  loop that writes led status on every iteration
-  if(temp > bias){ //Temp is too high, kick on heater and led
-    digitalWrite(LED, HIGH);
-    digitalWrite(RLY_OUT, HIGH);
-  } else { //Temp is low enough, turn off outputs
-    digitalWrite(LED, LOW);
-    digitalWrite(RLY_OUT, LOW);
-  }
-*/
-
-  if ((temp > bias) && (LED == 0)){ //Temp is too high and output is not already on
-    digitalWrite(LED, HIGH);
-    digitalWrite(RLY_OUT, HIGH);
-  } else if (temp > bias) { //Temp is too high, but output is already on
-    delay(25); //Wait 25ms, just for something to do
-  } else if ((temp <= bias) && (LED == 1)){ //Temp is low enough, and outputs are on.
-    digitalWrite(LED, LOW);
-    digitalWrite(RLY_OUT, LOW);
-  } else { //do nothing, outputs don't need switched again
-    delay(25);
-  }
-
+  //Control logic: Check temp in outer loop, inner loops check if relay status needs changed
+  if(temp > bias){ //Temp is too high
+    if(RLY_OUT == 0){ //Relay is off, turn it on
+      digitalWrite(LED, HIGH);
+      digitalWrite(RLY_OUT, HIGH);
+    }
+    //delay(10); //Necessary here??
+  } else { //Temp is low enough
+    if(RLY_OUT == 1){ //If relay is on, turn it off
+      digitalWrite(LED, LOW);
+      digitalWrite(RLY_OUT, LOW);
+    }
+    //delay(10);
+  }
   delay(25); //Delay 1/4 sec, to prevent hysterisis. Possibly increase this to >1 sec, depending on relay behavior.
 }

-int readAvg(int num, int pin){  //Take average of 'num' analogReads on 'pin'
+int readAvg(int num, int pin, int delayTime){  //Take average of 'num' analogReads on 'pin'. Delay time is total time for the loop.
   int x = 0; //Initialize t @ 0 to hold bias pot reading
+  int t = delayTime/num; //Calc delay time for each averaging loop.
+
   for(int i = 0; i < num; i++){ //Loop 5 times, add each reading
     x = x + analogRead(pin);
-    delay(10);
+    delay(t);
   }
+
   x = x / num; //take average
-
   return x;
 }

-void initBlink(int delay1, int delay2, int numLoops){ //Blink the led x times, delayTime between blinks
+void initBlink(int PIN, int delay1, int delay2, int numLoops){ //Blink the led x times, delayTime between blinks
   for(int i=0; i < numLoops; i++){
-    digitalWrite(LED, HIGH);
+    digitalWrite(PIN, HIGH);
     delay(delay1);
-    digitalWrite(LED, LOW);
+    digitalWrite(PIN, LOW);
     delay(delay2);
   }
 }


multi packed messages

multi packed messages

--- libraries/serial_using_structs/examples/serial_using_structs/serial_using_structs.ino
+++ libraries/serial_using_structs/examples/serial_using_structs/serial_using_structs.ino
@@ -14,22 +14,38 @@
     static const uint16_t TYPE = 100;
 };

+struct __attribute__ ( ( packed ) ) Text {
+    char c[32];
+    static const uint16_t TYPE = 200;
+};
+
 Pose pose;             /// object to send
+Text text;             /// object to send
 tuw::ComMessage msg;   /// object to hande the serial communication
+int loop_count;        /// defines which message should be send

 void setup() {
     init();
     Serial.begin ( 115200 );
-    msg.try_sync();   /// sync time
+    //msg.try_sync();   /// sync time
     delay ( 1000 );
-    pose.x = 140, pose.y = 0., pose.theta = 0.02;
+    pose.x = 140, pose.y = 10., pose.theta = 0.2;
+    sprintf(text.c,"Hello World!");
+    loop_count = 0;
 }

 void loop() {
     delay ( 1000 );
     pose.x += 1.;               /// we are increasing the x for debugging reasons
     msg.update_time(millis());  /// update time stamp
-    msg.set(pose).send();       /// sends pose message
+    msg.clear();
+    //msg.push(pose);
+    //msg.push(text);
+    msg.push_sync_request();
+    //if(loop_count % 2 == 0) msg.push(pose);       /// sends pose message
+    //if(loop_count % 2 == 1) msg.push(text);       /// sends pose message
+    msg.send();
+    /*
     if(msg.receive()) {         /// check for messages
       switch(msg.type){         /// check message type
         case tuw::ComHeader::TYPE_TIME: /// case time sync message
@@ -40,4 +56,6 @@
           break;
       }
     }
+    */
+    loop_count++;
 }


Match pitch of durationturn and durationgliss

Signed-off-by: Mark Knoop <f1b5a91d4d6ad523f2610114591c007e75d15084@markknoop.com>

--- src/sketch.ino
+++ src/sketch.ino
@@ -218,7 +218,8 @@
     stopTime = startTime + duration - (millis() - startTime);
     while(millis() < stopTime) {
         // avoid polling millis too often
-        for (int i=0; i<10; i++) onestep(pulse);
+        // use map() here to match pitch in _durationgliss
+        for (int i=0; i<10; i++) onestep(map(i, 0, 10, pulse, pulse));
     }
     for (int i=0; i<accelSteps; i++) {
         onestep(map(i, 0, accelSteps, pulse, startstoppulse));


Keeping history of roomNode changes

Keeping history of roomNode changes

--- nodes/roomNode/roomNode.ino
+++ nodes/roomNode/roomNode.ino
@@ -1,3 +1,14 @@
+//
+// Chezak Node - Jeelabs official Room Board (http://jeelabs.com/products/room-board)
+//
+// Original sketch: https://github.com/jcw/jeelib/blob/master/examples/RF12/roomNode/roomNode.ino
+//
+// Sensors:
+//  - SHT11 for temperature and humidity
+//  - LDR for light
+//  - PIR for motion
+//
+
 /// @dir roomNode
 /// New version of the Room Node (derived from rooms.pde).
 // 2010-10-19 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php
@@ -65,39 +76,32 @@
 #endif

 #if PIR_PORT
-    #define PIR_HOLD_TIME   30  // hold PIR value this many seconds after change
-    #define PIR_PULLUP      1   // set to one to pull-up the PIR input pin
-    #define PIR_INVERTED    1   // 0 or 1, to match PIR reporting high or low
+    #define PIR_PULLUP   1 // set to one to pull-up the PIR input pin
+    #define PIR_INVERTED 0 // 0 or 1, to match PIR reporting high or low

     /// Interface to a Passive Infrared motion sensor.
     class PIR : public Port {
         volatile byte value, changed;
-        volatile uint32_t lastOn;
+
     public:
         PIR (byte portnum)
-            : Port (portnum), value (0), changed (0), lastOn (0) {}
+            : Port (portnum), value (0), changed (0) {}

         // this code is called from the pin-change interrupt handler
         void poll() {
             // see http://talk.jeelabs.net/topic/811#post-4734 for PIR_INVERTED
             byte pin = digiRead() ^ PIR_INVERTED;
-            // if the pin just went on, then set the changed flag to report it
-            if (pin) {
-                if (!state())
-                    changed = 1;
-                lastOn = millis();
-            }
+
+            // if the pin changed then set the changed flag to report it
+            if (pin != state())
+                changed = 1;
+
             value = pin;
         }

         // state is true if curr value is still on or if it was on recently
         byte state() const {
             byte f = value;
-            if (lastOn > 0)
-                ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
-                    if (millis() - lastOn < 1000 * PIR_HOLD_TIME)
-                        f = 1;
-                }
             return f;
         }

@@ -150,35 +154,38 @@

     payload.lobat = rf12_lowbat();

-    #if SHT11_PORT
+#if SHT11_PORT
 #ifndef __AVR_ATtiny84__
-        sht11.measure(SHT11::HUMI, shtDelay);
-        sht11.measure(SHT11::TEMP, shtDelay);
-        float h, t;
-        sht11.calculate(h, t);
-        int humi = h + 0.5, temp = 10 * t + 0.5;
+    sht11.measure(SHT11::HUMI, shtDelay);
+    sht11.measure(SHT11::TEMP, shtDelay);
+    float h, t;
+    sht11.calculate(h, t);
+    int humi = h + 0.5, temp = 10 * t + 0.5;
 #else
-        //XXX TINY!
-        int humi = 50, temp = 25;
-#endif
-        payload.humi = smoothedAverage(payload.humi, humi, firstTime);
-        payload.temp = smoothedAverage(payload.temp, temp, firstTime);
-    #endif
-    #if LDR_PORT
-        ldr.digiWrite2(1);  // enable AIO pull-up
-        byte light = ~ ldr.anaRead() >> 2;
-        ldr.digiWrite2(0);  // disable pull-up to reduce current draw
-        payload.light = smoothedAverage(payload.light, light, firstTime);
-    #endif
-    #if PIR_PORT
-        payload.moved = pir.state();
-    #endif
+    //XXX TINY!
+    int humi = 50, temp = 25;
+#endif
+    payload.humi = smoothedAverage(payload.humi, humi, firstTime);
+    payload.temp = smoothedAverage(payload.temp, temp, firstTime);
+#endif
+
+#if LDR_PORT
+    ldr.digiWrite2(1);  // enable AIO pull-up
+    byte light = ~ ldr.anaRead() >> 2;
+    ldr.digiWrite2(0);  // disable pull-up to reduce current draw
+    payload.light = smoothedAverage(payload.light, light, firstTime);
+#endif
+
+#if PIR_PORT
+    payload.moved = pir.state();
+#endif
 }

 static void serialFlush () {
-    #if ARDUINO >= 100
-        Serial.flush();
-    #endif
+#if ARDUINO >= 100
+    Serial.flush();
+#endif
+
     delay(2); // make sure tx buf is empty before going back to sleep
 }

@@ -189,29 +196,29 @@
     rf12_sendWait(RADIO_SYNC_MODE);
     rf12_sleep(RF12_SLEEP);

-    #if SERIAL
-        Serial.print("ROOM ");
-        Serial.print((int) payload.light);
-        Serial.print(' ');
-        Serial.print((int) payload.moved);
-        Serial.print(' ');
-        Serial.print((int) payload.humi);
-        Serial.print(' ');
-        Serial.print((int) payload.temp);
-        Serial.print(' ');
-        Serial.print((int) payload.lobat);
-        Serial.println();
-        serialFlush();
-    #endif
+#if SERIAL
+    Serial.print("ROOM ");
+    Serial.print((int) payload.light);
+    Serial.print(' ');
+    Serial.print((int) payload.moved);
+    Serial.print(' ');
+    Serial.print((int) payload.humi);
+    Serial.print(' ');
+    Serial.print((int) payload.temp);
+    Serial.print(' ');
+    Serial.print((int) payload.lobat);
+    Serial.println();
+    serialFlush();
+#endif
 }

 // send packet and wait for ack when there is a motion trigger
 static void doTrigger() {
-    #if DEBUG
-        Serial.print("PIR ");
-        Serial.print((int) payload.moved);
-        serialFlush();
-    #endif
+#if DEBUG
+    Serial.print("PIR ");
+    Serial.print((int) payload.moved);
+    serialFlush();
+#endif

     for (byte i = 0; i < RETRY_LIMIT; ++i) {
         rf12_sleep(RF12_WAKEUP);
@@ -221,11 +228,12 @@
         rf12_sleep(RF12_SLEEP);

         if (acked) {
-            #if DEBUG
-                Serial.print(" ack ");
-                Serial.println((int) i);
-                serialFlush();
-            #endif
+#if DEBUG
+            Serial.print(" ack ");
+            Serial.println((int) i);
+            serialFlush();
+#endif
+
             // reset scheduling to start a fresh measurement cycle
             scheduler.timer(MEASURE, MEASURE_PERIOD);
             return;
@@ -234,10 +242,11 @@
         delay(RETRY_PERIOD * 100);
     }
     scheduler.timer(MEASURE, MEASURE_PERIOD);
-    #if DEBUG
-        Serial.println(" no ack!");
-        serialFlush();
-    #endif
+
+#if DEBUG
+    Serial.println(" no ack!");
+    serialFlush();
+#endif
 }

 void blink (byte pin) {
@@ -248,46 +257,45 @@
 }

 void setup () {
-    #if SERIAL || DEBUG
-        Serial.begin(57600);
-        Serial.print("\n[roomNode.3]");
-        myNodeID = rf12_config();
-        serialFlush();
-    #else
-        myNodeID = rf12_config(0); // don't report info on the serial port
-    #endif
+#if SERIAL || DEBUG
+    Serial.begin(57600);
+    Serial.print("\n[roomNode.3]");
+    myNodeID = rf12_config();
+    serialFlush();
+#else
+    myNodeID = rf12_config(0); // don't report info on the serial port
+#endif

     rf12_sleep(RF12_SLEEP); // power down

-    #if PIR_PORT
-        pir.digiWrite(PIR_PULLUP);
+#if PIR_PORT
+    pir.digiWrite(PIR_PULLUP);
 #ifdef PCMSK2
-        bitSet(PCMSK2, PIR_PORT + 3);
-        bitSet(PCICR, PCIE2);
+    bitSet(PCMSK2, PIR_PORT + 3);
+    bitSet(PCICR, PCIE2);
 #else
         //XXX TINY!
 #endif
-    #endif
+#endif

     reportCount = REPORT_EVERY;     // report right away for easy debugging
     scheduler.timer(MEASURE, 0);    // start the measurement loop going
 }

 void loop () {
-    #if DEBUG
-        Serial.print('.');
-        serialFlush();
-    #endif
-
-    #if PIR_PORT
-        if (pir.triggered()) {
-            payload.moved = pir.state();
-            doTrigger();
-        }
-    #endif
+#if DEBUG
+    Serial.print('.');
+    serialFlush();
+#endif
+
+#if PIR_PORT
+    if (pir.triggered()) {
+        payload.moved = pir.state();
+        doTrigger();
+    }
+#endif

     switch (scheduler.pollWaiting()) {
-
         case MEASURE:
             // reschedule these measurements periodically
             scheduler.timer(MEASURE, MEASURE_PERIOD);
@@ -305,4 +313,4 @@
             doReport();
             break;
     }
-}+}


Update BeepOnce.ino

Update BeepOnce.ino

--- examples/BeepOnce/BeepOnce.ino
+++ examples/BeepOnce/BeepOnce.ino
@@ -1,5 +1,5 @@
 /*
-	EasyBuzzer - BeepOnce Example
+	EasyBuzzer - Beep Once Example
 	This example shows you how to make a single beep at given frequency.
 	Copyright (c) 2017, Evert Arias
 	MIT License
@@ -25,4 +25,4 @@
 void loop() {
 	// Always call this function in the loop for EasyBuzzer to work.
 	EasyBuzzer.update();
-}+}


fix number of pins for T4

fix number of pins for T4

--- examples/adc_test/adc_test.ino
+++ examples/adc_test/adc_test.ino
@@ -49,12 +49,12 @@
 uint8_t adc_pins_diff[] = {A10, A11};

 #elif defined(ADC_TEENSY_4)  // Teensy 3.6
-#define PINS 25
-#define DIG_PINS 21
+#define PINS 14
+#define DIG_PINS 10
 #define PINS_DIFF 0
 uint8_t adc_pins[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8, A9, A10,
                       A11,A12,A13};
-uint8_t adc_pins_dig[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8, A9, A12,A13};
+uint8_t adc_pins_dig[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8, A9};
 uint8_t adc_pins_diff[] = {};
 #endif // defined


fix(webusb): Set initial data to 0

fix(webusb): Set initial data to 0

Initialize the "incoming" array of data to 0, so that when nothing is send to the USB DMX
Controller, all channels are turned off by default.

Fixes #32

--- arduino/sketch/LeonardoETH.ino
+++ arduino/sketch/LeonardoETH.ino
@@ -12,11 +12,17 @@
 // channels: Amount of DMX channels
 // pin: Pin to do read / write operations on the DMX shield
 // https://sourceforge.net/p/dmxlibraryforar/wiki/DMX%20Master/
-DMX_Master dmx_master(channels , 2);
+DMX_Master dmx_master(channels, 2);

+// Amount of incoming bytes via WebUSB
+// Array of bytes
+byte incoming[channels];

 // Run once on startup
 void setup() {
+  // Initialize incoming with 0
+  memset(incoming, 0, sizeof(incoming));
+
   // Wait until WebUSB connection is established
   while (!Serial) {
     ;
@@ -40,15 +46,8 @@
   dmx_master.enable();
 }

-
-
 // Run over and over again
 void loop() {
-
-  // Amount of incoming bytes via WebUSB
-  // Array of bytes
-  byte incoming[channels];
-
   // WebUSB is available
   if (Serial.available() > 0) {


working on conept 2

working on conept 2

--- project.ino
+++ project.ino
@@ -17,8 +17,9 @@

 #define PIN_STRIP 6
 #define PIN_SENSOR 7
+#define NUMBER_PINS 16

-Adafruit_NeoPixel strip = Adafruit_NeoPixel(16, PIN_STRIP, NEO_GRB + NEO_KHZ800);
+Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMBER_PINS, PIN_STRIP, NEO_GRB + NEO_KHZ800);

 void setup() {
   Serial.begin(9600);
@@ -30,13 +31,48 @@
 void loop(){
   triggerSensor();
   int distance = readSensor();
-  changeColor(distance);
+  changeColorLinear(distance);
   printDistance(distance);

-  delay(50);
+  delay(500);
 }

-long changeColor(int distance){
+long changeColorLinear(int distance){
+  int maxDistance = 160;
+  int minDistance = 10;
+
+  uint32_t leds[strip.numPixels()];
+
+  for(int i=0; i<strip.numPixels(); i++){
+    int value = min(i*20,255);
+    int green = 255-value;
+    int red = value;
+    leds[i] = strip.Color(red, green, 0);
+  }
+
+  distance = max(minDistance, distance);
+  distance = min(maxDistance, distance);
+
+  int height = (maxDistance - minDistance) / (distance - minDistance);
+
+  Serial.print("height: ");
+  Serial.print(height);
+  Serial.println();
+
+  for(uint16_t i=0; i<strip.numPixels(); i++) {
+
+    if(height >= i){
+      strip.setPixelColor(i, leds[i]);
+    }
+    else{
+      strip.setPixelColor(i, strip.Color(0,0,0));
+    }
+  }
+
+  strip.show();
+}
+
+long changeColorAll(int distance){
   int maxDistance = 200;
   int minDistance = 50;


Added hm1xTestHardware Sketch

Added hm1xTestHardware Sketch


Log rxsyms in compliance app

Log rxsyms in compliance app

--- examples/compliance-otaa-halconfig/compliance-otaa-halconfig.ino
+++ examples/compliance-otaa-halconfig/compliance-otaa-halconfig.ino
@@ -98,6 +98,7 @@
         u2_t        opmode;
         u2_t        fcntDn;
         u2_t        fcntUp;
+        u2_t        rxsyms;
         rps_t       rps;
         u1_t        txChnl;
         u1_t        datarate;
@@ -134,6 +135,7 @@
             pn->opmode = LMIC.opmode;
             pn->fcntDn = (u2_t) LMIC.seqnoDn;
             pn->fcntUp = (u2_t) LMIC.seqnoUp;
+            pn->rxsyms = LMIC.rxsyms;
             pn->rps = LMIC.rps;
             pn->txChnl = LMIC.txChnl;
             pn->datarate = LMIC.datarate;
@@ -484,6 +486,7 @@
                 printOpmode(e.opmode);
                 printTxend(e);
                 Serial.print(F(", delta ms ")); Serial.print(osticks2ms(e.time - e.txend));
+                Serial.print(F(", rxsyms=")); Serial.print(unsigned(e.rxsyms));
                 break;

             case EV_JOIN_TXCOMPLETE:


Updated YunSerialTerminal

Updated YunSerialTerminal

--- hardware/arduino/avr/libraries/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino
+++ hardware/arduino/avr/libraries/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino
@@ -20,11 +20,7 @@
  This example code is in the public domain.
  */

-<<<<<<< HEAD
-long baud = 9600;
-=======
-long baud = 57600;
->>>>>>> 113e28d86188899e529ced3fed04e4116e3f5a88
+long baud = 115200;

 // Pin 13 has an LED connected on most Arduino boards.
 // give it a name:
@@ -35,6 +31,8 @@
 void setup() {
   Serial.begin(baud);        // open serial connection to Linino
   Serial1.begin(baud);       // open serial connection via USB-Serial
+  Serial.println("Prova");   // Hello USB
+  Serial1.println("Prova1"); // Hello Linino

   // initialize the digital pin as an output.
   pinMode(led, OUTPUT);


Parameter Änderungen

Parameter Änderungen

--- QTRARawValuesExample.ino
+++ QTRARawValuesExample.ino
@@ -1,6 +1,7 @@
 #include <QTRSensors.h>

 int lastError = 0;
+int loopIndex;

 #define NUM_SENSORS             6  // number of sensors used
 #define NUM_SAMPLES_PER_SENSOR  4  // average 4 analog samples per sensor reading
@@ -12,7 +13,6 @@
 },
 NUM_SENSORS, NUM_SAMPLES_PER_SENSOR, EMITTER_PIN);
 unsigned int sensorValues[NUM_SENSORS];
-

 void setup() {
   //Setup Channel A
@@ -52,43 +52,41 @@

 void loop() {
-
+  loopIndex++;
+
   int position = qtra.readLine(sensorValues);
-  int M1 = 100;
-  int M2 = 100;
-  float KP = 0.001; //floating-point proportional constant
-  float KD = 3;   //floating-point derivative constant
-  int error = position - 2500;
+  int M1 = 200;
+  int M2 = 200;
+  float KP = 0.1; //floating-point proportional constant
+  float KD = 1;   //floating-point derivative constant
+  int propotionalToMid = position - 2500;

-  int motorSpeed = KP * error + KD * (error - lastError);
-  lastError = error;
+  int motorSpeed = KP * propotionalToMid + KD * (propotionalToMid - lastError);
+  lastError = propotionalToMid;

-  int m1Speed = M1 + motorSpeed;
-  int m2Speed = M2 - motorSpeed;
+  int m2Speed = M2 + motorSpeed;
+  int m1Speed = M1 - motorSpeed;

-  if (m1Speed < 0)
-    m1Speed = 0;
-  if (m2Speed < 0)
-    m2Speed = 0;
+  if (m1Speed < 0) m1Speed = 0;
+  if (m2Speed < 0) m2Speed = 0;

-  if (m1Speed > 180)
-    m1Speed = 180;
-  if (m2Speed > 180)
-    m2Speed = 180;
+  if (m1Speed > 180) m1Speed = 180;
+  if (m2Speed > 180) m2Speed = 180;

   motorA(m1Speed);
   motorB(m2Speed);

-   Serial.print(motorSpeed);
-   Serial.print('\t');
-    Serial.print(m1Speed);
-    Serial.print('\t');
-    Serial.print(m2Speed);
-    Serial.print('\t');
-    Serial.println();
-    delay(500);
-
-
+  sensorOutput();
+
+  //   Serial.print(motorSpeed);
+  //   Serial.print('\t');
+  //    Serial.print(m1Speed);
+  //    Serial.print('\t');
+  //    Serial.print(m2Speed);
+  //    Serial.print('\t');
+  //    Serial.println();
+
+
 }

 void motorA(int speed) {
@@ -98,7 +96,7 @@
 }

 void motorB(int speed) {
-  //Motor B forward
+  //Motor B forward
   digitalWrite(13, HIGH); //Establishes forward direction of Channel B
   analogWrite(11, speed);   //Spins the motor on Channel B

@@ -106,21 +104,22 @@

 void sensorOutput()
 {
-  // read calibrated sensor values and obtain a measure of the line position from 0 to 5000
-  // To get raw sensor values, call:
-  //  qtra.read(sensorValues); instead of unsigned int position = qtra.readLine(sensorValues);
-  unsigned int position = qtra.readLine(sensorValues);
-
-  // print the sensor values as numbers from 0 to 1000, where 0 means maximum reflectance and
-  // 1000 means minimum reflectance, followed by the line position
-  for (unsigned char i = 0; i < NUM_SENSORS; i++)
-  {
-    Serial.print(sensorValues[i]);
-
+  if (loopIndex % 100 == 0) {
+    // read calibrated sensor values and obtain a measure of the line position from 0 to 5000
+    // To get raw sensor values, call:
+    //  qtra.read(sensorValues); instead of unsigned int position = qtra.readLine(sensorValues);
+    unsigned int position = qtra.readLine(sensorValues);
+
+    // print the sensor values as numbers from 0 to 1000, where 0 means maximum reflectance and
+    // 1000 means minimum reflectance, followed by the line position
+    for (unsigned char i = 0; i < NUM_SENSORS; i++)
+    {
+      Serial.print(sensorValues[i]);
+      Serial.print('\t');
+
+    }
+    //Serial.println(); // uncomment this line if you are using raw values
+    Serial.println((int)position - 2500); // comment this line out if you are using raw values
   }
-  //Serial.println(); // uncomment this line if you are using raw values
-  Serial.println(position); // comment this line out if you are using raw values
-
-  delay(250);
 }
-
+


Fixe du array non valide

Fixe du array non valide

--- code/arduino/motors/motors.ino
+++ code/arduino/motors/motors.ino
@@ -132,11 +132,15 @@
           break;

       case 7:
+      // Required to define a new variable in a switch-case.
+      // http://stackoverflow.com/a/2392693
+      {
           // Distance
-          byte buf[] = { convert_imp_to_cm(counter_left),
-            convert_imp_to_cm(counter_right) };
+          byte buf[2]= { (byte) convert_imp_to_cm(counter_left),
+                (byte) convert_imp_to_cm(counter_right) };
           Wire.write(buf, 2);
           break;
+      }

       case 8:
           // Is Done


elliot had this cool idea about color transitions

--- rain2/rain2.ino
+++ rain2/rain2.ino
@@ -19,7 +19,7 @@

 #define VEL_DAMPING .9 // number between 0 and 1;
 #define MAX_VEL 1.5
-#define FALL_SPEED 30
+#define FALL_SPEED 100

 struct CRGB leds[TRUE_LED_COUNT];
 float aleds_vel[NUM_LEDS];
@@ -133,30 +133,19 @@

 CRGB dualbright2CRGB(float abright, float bbright){
   float r=0, b=0, g=0;
-  // if (abright > 0) {
-  //   r += abright / 2;
-  //   b += abright;
-  // } else if (abright <= 0) {
-  //   b -= 2 * abright / 3;
-  //   g -= abright / 5;
-  // }
-  // if (bbright > 0) {
-  //   r += 2 * bbright / 3;
-  //   g += bbright / 4;
-  // } else if (bbright <= 0) {
-  //   r -= bbright;
-  // }
   if (abright > 0) {
-    r += abright;
+    r += abright / 2;
+    b += abright;
   } else if (abright <= 0) {
-    b -= abright;
+    b -= 2 * abright / 3;
+    g -= abright / 5;
   }
   if (bbright > 0) {
     r += bbright;
-    g += bbright / 4;
+    b += bbright/3;
   } else if (bbright <= 0) {
-    b -= bbright;
-    g -= bbright / 4;
+    b -= abright / 2;
+    g -= abright / 5;
   }
   return CRGB(r/2, g/2, 2 * b/3);
 }
@@ -171,13 +160,13 @@
     bnext_leds_brightness[i] = next_for_idx(i, bleds_brightness, bleds_vel);
   }
   if (random(10) == 0){
-    if (atoggle) anext_leds_brightness[random(NUM_LEDS)] = 30.0;
-    else anext_leds_brightness[random(NUM_LEDS)] = - 30.0;
+    if (atoggle) anext_leds_brightness[random(NUM_LEDS)] = 60.0;
+    else anext_leds_brightness[random(NUM_LEDS)] = - 60.0;
     atoggle = !atoggle;
   }
   if (random(10) == 0){
-    if (btoggle) bnext_leds_brightness[random(NUM_LEDS)] = 30.0;
-    else bnext_leds_brightness[random(NUM_LEDS)] = - 30.0;
+    if (btoggle) bnext_leds_brightness[random(NUM_LEDS)] = 60.0;
+    else bnext_leds_brightness[random(NUM_LEDS)] = - 60.0;
     btoggle = !btoggle;
   }
   for (int k = 0; k<NUM_LEDS; k++){


Add missing import to main .ino file

Add missing import to main .ino file

--- bolt-arduino.ino
+++ bolt-arduino.ino
@@ -7,6 +7,7 @@
 #include "game.h"
 #include "const.h"
 #include "clock.h"
+#include "controller.h"

 void setup() {


reduce modes; change "button" to "switch"

first major galaxytopper software update:

I replaced the button in the band with a tilt-switch pointed nearly
vertically. Now when I tip the hat it changes patterns. I also set it up
to go back to stealth mode between patterns.

Patterns have been reduced to the following three:
 * Nebula  -- same as before
 * Rainbow -- same as before
 * Sparkle -- now randomly changes its speed and limits itself to highly
              saturated colors

Switched to a better HSV->RGB conversion

I've also got the beginnings of a "stars" mode that's supposed to
twinkle, but I need to do more work on that.

--- galaxytopper.ino
+++ galaxytopper.ino
@@ -5,28 +5,23 @@
  *
  * It uses 6 ShiftBrite pixels to drive a "galaxy" of points of light poking
  * through the felt of a simple, felt top hat. The hat has several different
- * modes and more can be added fairly easily. There is a momentary pushbutton
- * hidden under the bow on the band to cycle through the modes. To keep things
- * fresh and interesting the pushbutton seeds the pRNG with the current value
- * of millis() when pushed.
+ * modes and more can be added fairly easily. There is a tilt switch taped into
+ * the brim of the hat, positioned nearly vertically. Tipping the hat advances
+ * the pattern displayed, alternating with the "stealth" pattern. To keep
+ * things fresh and interesting we seed the pRNG with the current value of
+ * millis() when the switch activates.
  *
  * MODES:
- *  - Stealth: All pixels are off, leaving the hat dark.
- *  - Sparkle: each pixel picks a random color, waits a short time, and picks a
- *      new one
- *  - Rainbow: Each pixel fades around the color wheel. Pixels are offset from
+ *  - Stealth:
+ *		All pixels are off, leaving the hat dark.
+ *  - Nebula:
+ *		Each pixel fades randomly through blue/white/purple colors
+ *      creating a rippling, twinkling pattern in the colors of the night sky
+ *  - Sparkle:
+ *		Each pixel flickers quickly from one random value to another
+ *  - Rainbow:
+ *		Each pixel fades around the color wheel. Pixels are offset from
  *      one another to give a more active pattern
- *  - Nebula: each pixel fades randomly through blue/white/purple colors
- *      creating a rippling, twinkling pattern in the colors of the night sky
- *  - Christmas Lights: Pixels cycle through the soft colors of old strings of
- *      Christmas lights. Colors are nominally red, yellow, green, and blue,
- *      TODO: but in practice are washed out and warmed over
- *  - Christmas: Pixels alternate between red and green.
- *
- * TODO:
- * I'd really like to add a couple more pixels tied directly into certain
- * patterns (alchemical symbols?) that I can have illuminate at random or on
- * command, but I'm not sure if that'll work out.
  */

@@ -36,7 +31,7 @@

 /* Constants */
 #define LATCH_PIN    9  // replace with pin you use for the ShiftBrite latch
-#define BUTTON_PIN   3  // pin used for the button to cycle modes
+#define SWITCH_PIN   3  // pin used for the switch to cycle modes
 #define NUM_LEDS     6  // Number of LEDs in your chain
 #define NUM_MODES    6  // Number of light modes the topper supports
 #define FPS        100  // number of times per second to update shiftbrites
@@ -45,15 +40,18 @@
 /* Predeclarations */
 // Necessary to avoid confusing particle's preprocessor
 // see https://docs.particle.io/reference/firmware/core/#preprocessor
+void dark_tick(Ticker *t, unsigned long tick);
+void random_tick(Ticker *t, unsigned long tick);
 void colorwheel_tick(Ticker *t, unsigned long tick);
-void cycling_tick(Ticker *t, unsigned long tick);
-void fading_cycling_tick(Ticker *t, unsigned long tick);
 void targeted_tick(Ticker *t, unsigned long tick);
-void dark_tick(Ticker *t, unsigned long tick);
+void hsv_targeted_tick(Ticker *t, unsigned long tick);
+
 TickerRgb hsv2rgb(double hue, double sat, double value);

 /* Define Objects */
 ShiftBrite sb(NUM_LEDS, LATCH_PIN);
+//TODO: see if this works
+//Ticker Tickers[NUM_LEDS];
 Ticker Tickers[NUM_LEDS] = {
 	Ticker(&dark_tick, 0, 0,  0),
 	Ticker(&dark_tick, 0, 0,  0),
@@ -68,10 +66,10 @@
 unsigned long tick_delay  = 1000 / TPS;
 unsigned long tick, last_tick, last_frame = 0;

-/* Button to switch modes */
+/* Switch to switch modes */
 int current_mode = 0;
 volatile int           mode_change_requested = 0;
-volatile unsigned long button_last_triggered = 0;
+volatile unsigned long switch_last_triggered = 0;

 void setup()
 {
@@ -79,9 +77,9 @@
 	sb.begin();
 	sb.show();

-	// Set up mode-change button
-	pinMode(BUTTON_PIN, INPUT_PULLUP);
-	attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), trigger_change, FALLING);
+	// Set up mode-change switch
+	pinMode(SWITCH_PIN, INPUT_PULLUP);
+	attachInterrupt(digitalPinToInterrupt(SWITCH_PIN), trigger_change, FALLING);

 	// Initialize tickers
 	mode_stealth();
@@ -118,8 +116,8 @@
  * MODE SETUP FUNCTIONS *
  ************************/
 void trigger_change() {
-	if (millis() - button_last_triggered > 600) {
-		button_last_triggered = millis();
+	if (millis() - switch_last_triggered > 600) {
+		switch_last_triggered = millis();
 		mode_change_requested = 1;
 	}
 }
@@ -134,19 +132,13 @@
 			mode_stealth();
 			break;
 		case 1:
+			mode_nebula();
+			break;
+		case 3:
+			mode_rainbow();
+			break;
+		case 5:
 			mode_sparkle();
-			break;
-		case 2:
-			mode_rainbow();
-			break;
-		case 3:
-			mode_nebula();
-			break;
-		case 4:
-			mode_christmas_lights();
-			break;
-		case 5:
-			mode_christmas();
 			break;
 		default:
 			mode_stealth();
@@ -169,41 +161,37 @@
 	for (int i = 0; i < NUM_LEDS; ++i) {
 		Tickers[i] = Ticker(&targeted_tick, 3, 0, i * 5 + 1);

-		Tickers[i].targets[0] = {red: random(0,1023), green: random(0,1023), blue: random(0,1023)};
+		Tickers[i].current    = {red: random(0, 1023), green: random(0, 1023), blue: random(511, 1023)};
+		Tickers[i].targets[0] = {red: random(0, 1023), green: random(0, 1023), blue: random(511, 1023)};
+
 		Tickers[i].targets[1] = {red: 0, green: 0, blue: 511};
 		Tickers[i].targets[2] = {red: 1023, green: 1023, blue: 1023};
 	}
 }

+//FIXME: Make it flicker faster than nebula.
+void mode_stars()
+{
+	// Use targeting tickers constrained to be white
+	// to make a twinkling starfield
+	for (int i = 0; i < NUM_LEDS; ++i) {
+		Tickers[i] = Ticker(&hsv_targeted_tick, 3, 0, i * 5 + 1);
+
+		int16_t value = random(0, 1023);
+		Tickers[i].current    = {red: value, green: value, blue: value};
+		Tickers[i].targets[0] = {red: value, green: value, blue: value};
+
+		// We're lying here and using TickerRgb's "red", "green", and "blue"
+		// data members for "hue", "saturation", and "value" respectively.
+		Tickers[i].targets[1] = {red: 0, green: 0, blue: 0};
+		Tickers[i].targets[2] = {red: 0, green: 0, blue: 1023};
+	}
+}
+
 void mode_sparkle()
 {
 	for (int i = 0; i < NUM_LEDS; ++i) {
-		Tickers[i] = Ticker(&random_tick, 0, 2, i);
-	}
-}
-
-void mode_christmas_lights()
-{
-	for (int i = 0; i < NUM_LEDS; ++i) {
-		// Slow by 2^6
-		Tickers[i] = Ticker(&cycling_tick, 4, 6, i);
-
-		//TODO: Adjust these values to taste to simulate christmas lights
-		Tickers[i].targets[0] = {red: 1023, green:    0, blue:    0}; // Red
-		Tickers[i].targets[1] = {red: 1023, green: 1023, blue:    0}; // Yellow
-		Tickers[i].targets[2] = {red:    0, green: 1023, blue:    0}; // Green
-		Tickers[i].targets[3] = {red:    0, green:    0, blue: 1023}; // Blue
-	}
-}
-
-void mode_christmas()
-{
-	for (int i = 0; i < NUM_LEDS; ++i) {
-		// Slow by 2^6
-		Tickers[i] = Ticker(&cycling_tick, 2, 6, i);
-
-		Tickers[i].targets[0] = {red: 1023, green:    0, blue:    0}; // Red
-		Tickers[i].targets[1] = {red:    0, green: 1023, blue:    0}; // Green
+		Tickers[i] = Ticker(&random_tick, 0, 3, i);
 	}
 }

@@ -225,6 +213,18 @@
 }

 /*
+ * Picks a random color and switches to it.
+ * Also randomizes how quickly it moves to the next color.
+ * This tick function does not use any targets.
+ */
+void random_tick(Ticker *t, unsigned long tick)
+{
+	if (tick % (1 << t->speed_adjust)) {return;}
+	t->speed_adjust = random(2,5);
+	t->current = hsv2rgb((double)random(0,1023)/1023, (double)random(767,1023)/1023, (double)random(0,1023)/1023);
+}
+
+/*
  * Cycles around the color wheel by using tick to compute the hue (value and
  * saturation are held constant at 1).
  *
@@ -238,65 +238,7 @@
 void colorwheel_tick(Ticker *t, unsigned long tick)
 {
 	int16_t hue = ((tick >> t->speed_adjust) + t->offset) % 360;
-	t->current = hsv2rgb((double)hue, 1.0, 1.0);
-}
-
-/*
- * Picks a random color and switches to it.
- *
- * By default it switches every tick. Slow this by 2^n by setting Ticker's
- * speed_adjust to n.
- *
- * This tick function does not use any targets
- */
-void random_tick(Ticker *t, unsigned long tick)
-{
-	if (tick % (1 << t->speed_adjust)) {return;}
-	t->current = {red: random(0,1023), green: random(0,1023), blue: random(0,1023)};
-}
-
-/*
- * Cycles through a fixed list of target colors.
- *
- * By default moves to the next color in the cycle every tick. Slow this
- * by 2^n by setting Ticker's speed_adjust to n.
- *
- * Advance the position in the cycle with Ticker's offset. This can be used to
- * sync multiple cycling_tick tickers into a string.
- *
- * This tick function uses as many targets as you choose to give the Ticker.
- */
-void cycling_tick(Ticker *t, unsigned long tick)
-{
-	int current_index = ((tick >> t->speed_adjust) + t->offset) % t->num_targets;
-	t->current = t->targets[current_index];
-}
-
-/*
- * Cycles through a fixed list of target colors, fading between them.
- *
- * Fading from one color to the next takes about a second. TODO: make this
- * dynamic via Ticker's speed_adjust.
- *
- * Advance the position in the cycle with Ticker's offset. This can be used to
- * sync multiple cycling_tick tickers into a string.
- *
- * This tick function uses as many targets as you choose to give the Ticker.
- */
-void fading_cycling_tick(Ticker *t, unsigned long tick)
-{
-	int previous_index = ((tick / TPS) + t->offset) % t->num_targets; // Update target once per second.
-	TickerRgb previous_color = t->targets[previous_index];
-	TickerRgb next_color     = t->targets[(previous_index + 1) % t->num_targets];
-
-	int16_t red_delta     = next_color.red       - previous_color.red;
-	int16_t current_red   = previous_color.red   + ((red_delta * (tick % TPS)) / TPS);
-	int16_t green_delta   = next_color.green     - previous_color.green;
-	int16_t current_green = previous_color.green + ((green_delta * (tick % TPS)) / TPS);
-	int16_t blue_delta    = next_color.blue      - previous_color.blue;
-	int16_t current_blue  = previous_color.blue  + ((blue_delta * (tick % TPS)) / TPS);
-
-	t->current = {red: current_red, green: current_green, blue: current_blue};
+	t->current = hsv2rgb((double)hue/360, 1.0, 1.0);
 }

 /*
@@ -348,6 +290,45 @@
 	current->blue  += stepToward(target->blue,  current->blue,  step_size);
 }

+/*
+ * As targeted_tick except the minima and maxima are given in HSV coordinates.
+ * This is a very lazy bit of copypasta from targeted_tick -- only the
+ * constraints are actually HSV colors; the current and target colors are still
+ * RGB and the steps occur in RGB space.
+ */
+void hsv_targeted_tick(Ticker *t, unsigned long tick)
+{
+	// speed_adjust keeps us from ticking on certain cycles
+	if (tick % (1 << t->speed_adjust)) {return;}
+
+	TickerRgb* current = &t->current;
+	TickerRgb* target  = &t->targets[0];
+	TickerRgb  minima  = t->targets[1];
+	TickerRgb  maxima  = t->targets[2];
+	int step_size = t->offset;
+
+	if (   current->red   == target->red
+		&& current->green == target->green
+		&& current->blue  == target->blue)
+	{
+		// We've reached the target! Pick a new one. We're lying here and using
+		// the "red", "green", and "blue" data members of minima and maxima for
+		// "hue", "saturation", and "value" respectively.
+		double hue        = (double)random(minima.red,   maxima.red)   / (double)1023;
+		double saturation = (double)random(minima.green, maxima.green) / (double)1023;
+		double value      = (double)random(minima.blue,  maxima.blue)  / (double)1023;
+		*target = hsv2rgb(hue, saturation, value);
+
+		// And just for fun let's also randomize the fade speed!
+		t->offset       = skew(random(1, 100), 5, 50, 100);
+		t->speed_adjust = random(0, 1);
+	}
+	// Still working towards the target. Take a step in the right direction
+	current->red   += stepToward(target->red,   current->red,   step_size);
+	current->green += stepToward(target->green, current->green, step_size);
+	current->blue  += stepToward(target->blue,  current->blue,  step_size);
+}
+
 /*** HELPER FUNCTIONS ***/

 /*
@@ -382,67 +363,31 @@

 /*
  * This function converts an HSV value into an RGB value.
- * Code taken from StackOverflow user DavidH:
- *   http://stackoverflow.com/questions/3018313/algorithm-to-convert-rgb-to-hsv-and-hsv-to-rgb-in-range-0-255-for-both
- */
-TickerRgb hsv2rgb(double hue, double sat, double value)
-{
-	double sextant, chroma, q, t, ff;
-	double red, blue, green;
-	long  i;
-	TickerRgb   out;
-
-	if(sat <= 0.0) {
-		red   = value;
-		green = value;
-		blue  = value;
-		return out;
-	}
-
-	sextant = hue;
-	if(sextant >= 360.0) sextant = 0.0;
-	sextant /= 60.0;
-	i = (long)sextant;
-	ff = sextant - i;
-	chroma = value * (1.0 - sat);
-	q = value * (1.0 - (sat * ff));
-	t = value * (1.0 - (sat * (1.0 - ff)));
-
-	switch(i) {
-		case 0:
-			red   = value;
-			green = t;
-			blue  = chroma;
-			break;
-		case 1:
-			red   = q;
-			green = value;
-			blue = chroma;
-			break;
-		case 2:
-			red   = chroma;
-			green = value;
-			blue  = t;
-			break;
-		case 3:
-			red   = chroma;
-			green = q;
-			blue  = value;
-			break;
-		case 4:
-			red   = t;
-			green = chroma;
-			blue  = value;
-			break;
-		case 5:
-		default:
-			red   = value;
-			green = chroma;
-			blue  = q;
-			break;
-	}
-	out.red   = (int16_t)(red   * 1023);
-	out.green = (int16_t)(green * 1023);
-	out.blue  = (int16_t)(blue  * 1023);
+ * Code taken from github user ratkins:
+ *   https://github.com/ratkins/RGBConverter
+ */
+TickerRgb hsv2rgb(double h, double s, double v)
+{
+	double r, g, b;
+	TickerRgb out;
+
+	int i = int(h * 6);
+	double f = h * 6 - i;
+	double p = v * (1 - s);
+	double q = v * (1 - f * s);
+	double t = v * (1 - (1 - f) * s);
+
+	switch(i % 6){
+		case 0: r = v, g = t, b = p; break;
+		case 1: r = q, g = v, b = p; break;
+		case 2: r = p, g = v, b = t; break;
+		case 3: r = p, g = q, b = v; break;
+		case 4: r = t, g = p, b = v; break;
+		case 5: r = v, g = p, b = q; break;
+	}
+
+	out.red   = (int16_t)(r * 1023);
+	out.green = (int16_t)(g * 1023);
+	out.blue  = (int16_t)(b * 1023);
 	return out;
 }


Show error code in sensor measurements.

Show error code in sensor measurements.

Now that error code isn't a CLOUD VARIABLE™, it needs to be exposed
somehow. This was really useful for figuring out that I'd plugged the
Photon power shield into the I²C shield backwards.

--- src/wxs.ino
+++ src/wxs.ino
@@ -76,9 +76,12 @@
 int
 takeMeasurements(String unused)
 {
+	char err[32];
 	weather.Updated = Time.now();
 	if (!tempSensor.Update()) {
-		MSG("failed to update temperature");
+		sprintf(err, "failed to update temperature: %d",
+			tempSensor.ErrorCode());
+		MSG(err);
 		weather.Error = tempSensor.ErrorCode();
 		return -1;
 	}
@@ -86,7 +89,9 @@
 	weather.Humidity = tempSensor.RelativeHumidity();

 	if (!barometer.Update()) {
-		MSG("failed to update pressure");
+		sprintf(err, "failed to update pressure: %d",
+			barometer.ErrorCode());
+		MSG(err);
 		weather.Error = barometer.ErrorCode();
 		return -1;
 	}


back to blue... red failed

back to blue... red failed

--- Scripts/fourelevenseventeen.ino
+++ Scripts/fourelevenseventeen.ino
@@ -50,38 +50,38 @@
  void loop() {

     if (timeOut+15700 < millis()) {        // idle state - 'breathe' the top and bottom LED to show program is looping
-       uint32_t blue = (0, 0, breathe);
+       uint32_t red = (0, 0, breathe);
        breathe = breathe + change;
-       strip.setPixelColor(0, blue);
-       strip.setPixelColor(27, blue);
-       strip.setPixelColor(28, blue);
-       strip.setPixelColor(57, blue);
-       strip.setPixelColor(58, blue);
-       strip.setPixelColor(87, blue);
-       strip.setPixelColor(88, blue);
-       strip.setPixelColor(117, blue);
-       strip.setPixelColor(118, blue);
-       strip.setPixelColor(147, blue);
-       strip.setPixelColor(148, blue);
-       strip.setPixelColor(177, blue);
-       strip.setPixelColor(178, blue);
-       strip.setPixelColor(207, blue);
-       strip.setPixelColor(208, blue);
-       strip.setPixelColor(237, blue);
-       strip.setPixelColor(238, blue);
-       strip.setPixelColor(267, blue);
-       strip.setPixelColor(268, blue);
-       strip.setPixelColor(297, blue);
-       strip.setPixelColor(298, blue);
-       strip.setPixelColor(327, blue);
-       strip.setPixelColor(328, blue);
-       strip.setPixelColor(357, blue);
-       strip.setPixelColor(358, blue);
-       strip.setPixelColor(387, blue);
-       strip.setPixelColor(388, blue);
-       strip.setPixelColor(417, blue);
-       strip.setPixelColor(418, blue);
-       strip.setPixelColor(446, blue);
+       strip.setPixelColor(0, red);
+       strip.setPixelColor(27, red);
+       strip.setPixelColor(28, red);
+       strip.setPixelColor(57, red);
+       strip.setPixelColor(58, red);
+       strip.setPixelColor(87, red);
+       strip.setPixelColor(88, red);
+       strip.setPixelColor(117, red);
+       strip.setPixelColor(118, red);
+       strip.setPixelColor(147, red);
+       strip.setPixelColor(148, red);
+       strip.setPixelColor(177, red);
+       strip.setPixelColor(178, red);
+       strip.setPixelColor(207, red);
+       strip.setPixelColor(208, red);
+       strip.setPixelColor(237, red);
+       strip.setPixelColor(238, red);
+       strip.setPixelColor(267, red);
+       strip.setPixelColor(268, red);
+       strip.setPixelColor(297, red);
+       strip.setPixelColor(298, red);
+       strip.setPixelColor(327, red);
+       strip.setPixelColor(328, red);
+       strip.setPixelColor(357, red);
+       strip.setPixelColor(358, red);
+       strip.setPixelColor(387, red);
+       strip.setPixelColor(388, red);
+       strip.setPixelColor(417, red);
+       strip.setPixelColor(418, red);
+       strip.setPixelColor(446, red);
        strip.show();
        if (breathe == 100 || breathe == 0) change = -change;      // breathe the LED from 0 = off to 100 = fairly bright
        if (breathe == 100 || breathe == 0); delay (100);           // Pause at beginning and end of each breath


can accept command to silence the buzzer, e.g. via bluetooth. code improvements.

--- arduino-singing-rain-detector.ino
+++ arduino-singing-rain-detector.ino
@@ -1,51 +1,51 @@
 #include "pitches.h"
 #include "melody.h"

-const int sensorMin = 0;     // sensor minimum
-const int sensorMax = 1024;  // sensor maximum
+const int RAIN_THRESHOLD = 700;
+const int SENSOR_PIN = A0;
+const int BUZZER_PIN = 2;
+
+const int SILENCE_COMMAND = 1;
+
+enum mode {SOUND_ON, SOUND_OFF};
+enum mode deviceMode = SOUND_ON;

 void setup() {
-  Serial.begin(9600);
+  Serial.begin(115200);
 }

 void loop() {
-  // read the sensor on analog A0:
-  int sensorReading = analogRead(A0);
-  // map the sensor range (four options):
-  // ex: 'long int map(long int, long int, long int, long int, long int)'
-  int range = map(sensorReading, sensorMin, sensorMax, 0, 3);

-  // range value:
-  switch (range) {
-    case 0:    // Sensor getting wet
-      Serial.println("Flood");
+  if (Serial.available()) {
+    if (Serial.read() == SILENCE_COMMAND) {
+      deviceMode = SOUND_OFF;
+    }
+  }
+
+  int sensorReading = analogRead(SENSOR_PIN);
+  Serial.println(sensorReading);
+
+  if (sensorReading < RAIN_THRESHOLD) {
+    if (deviceMode != SOUND_OFF) {
+      //Serial.println("I'm singing in the rain");
       buzzerSound();
-      break;
-    case 1:    // Sensor getting wet
-      Serial.println("Rain Warning");
-      buzzerSound();
-      break;
-    case 2:    // Sensor dry - To shut this up delete the " Serial.println("Not Raining"); " below.
-      Serial.println("Not Raining");
-      break;
+    }
   }
-  delay(1);  // delay between reads
+  else {
+    deviceMode = SOUND_ON;
+  }
+
+  delay(1000*20); // delay between reads = 1 minute
 }

 void buzzerSound() {
-  Serial.println(sizeof(melody));
-  Serial.println(sizeof(melody[0]));
   for (int thisNote = 0; thisNote < sizeof(melody) / sizeof(melody[0]); thisNote++) {
     int noteDuration = 1000 * melody[thisNote].duration;
-    Serial.println(melody[thisNote].duration);
-    Serial.println(melody[thisNote].duration);
-    tone(2, melody[thisNote].pitch, noteDuration);
+    tone(BUZZER_PIN, melody[thisNote].pitch, noteDuration);

     // to distinguish the notes, set a minimum time between them.
     // the note's duration + 30% seems to work well:
     int pauseBetweenNotes = noteDuration * 1.30;
     delay(pauseBetweenNotes);
-    // stop the tone playing:
-    // noTone(2);
   }
 }


Stream multiple byte fix

Stream multiple byte fix

--- arduino/PaddleFish/PaddleFish.ino
+++ arduino/PaddleFish/PaddleFish.ino
@@ -343,7 +343,7 @@

 void streamAddCmd(char *buffer)
 {
-  int start = streamCmdArray[0]*STREAM_LENGTH+5;
+  int start = ((int)streamCmdArray[0]*STREAM_LENGTH)+5;
   for (int i=0;i<5;i++)
     streamCmdArray[start+i]=buffer[i];
   streamCmdArray[0]++;
@@ -380,14 +380,6 @@
 */
 void heartBeat()
 {
-  //char buff[streamCmdArray[1]+1+4+2]
-
-  /*buff[0] = CMD_STREAM_START;
-  buff[1] = time & 0xFF;
-  buff[2] = (time>>8) & 0xFF;
-  buff[3] = (time>>16) & 0xFF;
-  buff[4] = (time>>24) & 0xFF;*/
-
   Serial.write(CMD_STREAM_START);
   Serial.write(streamCmdArray[1]+4+2);

@@ -398,21 +390,15 @@
   Serial.write((time>>16) & 0xFF);
   Serial.write((time>>24) & 0xFF);
   // Send device data
-  //int j=0;
   for (int dev=0;dev<streamCmdArray[0];dev++)
   {
     int start = 5 + (dev * STREAM_LENGTH);
     char* recBuf = pfReadBytes(streamCmdArray[start],streamCmdArray[start+1],streamCmdArray[start+2]);
-    //for (int=0;i<streamCmdArray[start+2];i++)
-      //buff[5+i+j] = recBuf[i];
-    //j=j+streamCmdArray[start+2];
-    Serial.write(recBuf);
+    for (int i=0;i<streamCmdArray[start+2];i++)
+      Serial.write(recBuf[i]);
   }

   char CRC = 0x00;
-  //buff[5+j]=CRC;
-  //buff[5+j+1]=CMD_STREAM_END;
-  //Serial.write(buff);
   Serial.write(CRC);
   Serial.write(CMD_STREAM_END);
   //blinkLed();
@@ -427,17 +413,9 @@
   char* sendNull = {0x00};
   sendData[0]=regAddress;
   lwi2c.i2c_start();
-  /*if (!lwi2c.get_last_error())
-    return sendNull;*/
   lwi2c.i2c_write(devAddress,1,(char*)sendData);
-  /*if (!lwi2c.get_last_error())
-    return sendNull;*/
   lwi2c.i2c_repeated_start();
-  /*if (!lwi2c.get_last_error())
-    return sendNull;*/
   char* receiveBuffer = lwi2c.i2c_read(devAddress,length);
-  /*if (!lwi2c.get_last_error())
-    return sendNull;*/
   lwi2c.i2c_stop();

   if (0x00 != lwi2c.get_last_error())
@@ -502,21 +480,6 @@
   Serial.write(CMD_ESC);
 }

-void disableInterrupt()
-{
-  /*Timer1.detachInterrupt();
-  Timer1.stop();*/
-}
-
-void enableInterrupt(long period)
-{
-  /*Timer1.initialize(period);
-
-  // attach timer interrupt
-  Timer1.attachInterrupt(heartBeat);*/
-
-}
-
 boolean receiveBytes(int length,char* buffer)
 {
   Serial.readBytes(buffer,length);


Updating light test

Updating light test

--- arduino/light_test/light_test.ino
+++ arduino/light_test/light_test.ino
@@ -15,11 +15,38 @@

 void loop()
 {
+    setLights(LOW, 0);
+
+    delay(1000);
+
+    setLights(HIGH, 200);
+
+    delay(500);
+
+    blinkLights();
+    blinkLights();
+    blinkLights();
+
+    delay(2000);
+}
+
+void setLights(int value, int msDelay)
+{
     for (int i = 0; i < cLights; i++)
     {
-        digitalWrite(rgLights[i], HIGH);
+        digitalWrite(rgLights[i], value);
+        delay(msDelay);
     }
-
-    delay(10000);
 }

+void blinkLights()
+{
+    const int msDelay = 400;
+
+    setLights(LOW, 0);
+    delay(400);
+
+    setLights(HIGH, 0);
+    delay(400);
+
+}


Balancer example: Added two spaces.

Balancer example: Added two spaces.

--- examples/Balancer/Balancer.ino
+++ examples/Balancer/Balancer.ino
@@ -90,13 +90,13 @@

 void standUp()
 {
-  motors.setSpeeds(0,0);
+  motors.setSpeeds(0, 0);
   buzzer.play("!frfr");
   while (buzzer.isPlaying());
   buzzer.play(">c2");
   motors.setSpeeds(-MOTOR_SPEED_LIMIT, -MOTOR_SPEED_LIMIT);
   delay(400);
-  motors.setSpeeds(150,150);
+  motors.setSpeeds(150, 150);
   for (uint8_t i = 0; i < 20; i++)
   {
     delay(UPDATE_TIME_MS);


report

report

--- _49-emontxv2-esp-01-i2c/esp-01/esp-01.ino
+++ _49-emontxv2-esp-01-i2c/esp-01/esp-01.ino
@@ -100,6 +100,18 @@

 void data_isr() {
   bdata_is_rdy = digitalRead(DATA_IS_RDY_PIN);
+}
+
+void ICACHE_RAM_ATTR sendUdpmsg(String msgtosend) {
+  unsigned int msg_length = msgtosend.length();
+  byte* p = (byte*)malloc(msg_length);
+  memcpy(p, (char*) msgtosend.c_str(), msg_length);
+
+  udp.beginPacket(influxdbudp, 8089);
+  udp.write(p, msg_length);
+  udp.endPacket();
+  free(p);
+  delay(100);
 }

 void ICACHE_RAM_ATTR sendUdpSyslog(String msgtosend) {
@@ -253,9 +265,36 @@
   sendUdpSyslog(syslogPayload);
 }

+void ICACHE_RAM_ATTR sendtoInfluxdb() {
+  String udppayload = "emontxv2,device=esp-01 ";
+  udppayload += "F=";
+  udppayload += ESP.getCpuFreqMHz();
+  udppayload += "i,pls_no=";
+  udppayload += sensor_data.pls_no;
+  udppayload += "i,pls_ts=";
+  udppayload += sensor_data.pls_ts;
+  udppayload += "i,pls_p=";
+  udppayload += pls_p;
+  udppayload += "i,ct1_rp=";
+  udppayload += sensor_data.ct1_rp;
+  udppayload += "i,ct1_ap=";
+  udppayload += sensor_data.ct1_ap;
+  udppayload += "i,ct1_vr=";
+  udppayload += sensor_data.ct1_vr;
+  udppayload += "i,ct1_ir=";
+  udppayload += sensor_data.ct1_ir;
+  udppayload += "i,ct2_rp=";
+  udppayload += sensor_data.ct2_rp;
+  udppayload += "i,ct3_rp=";
+  udppayload += sensor_data.ct3_rp;
+  udppayload += "i,door=";
+  udppayload += sensor_data.door;
+  udppayload += "i";
+
+  sendUdpmsg(udppayload);
+}
+
 bool ICACHE_RAM_ATTR get_i2c_data() {
-  //detachInterrupt(digitalPinToInterrupt(DATA_IS_RDY_PIN));
-  //delayMicroseconds(5);
   if (digitalRead(DATA_IS_RDY_PIN)) {
     pinMode(DATA_IS_RDY_PIN, OUTPUT);
     digitalWrite(DATA_IS_RDY_PIN, LOW);
@@ -271,8 +310,6 @@
   } else {
     return false;
   }
-  //delayMicroseconds(5);
-  //attachInterrupt(digitalPinToInterrupt(DATA_IS_RDY_PIN), data_isr, RISING);
 }

 void setup() {
@@ -346,12 +383,11 @@
       } else {
         pls_p = 0;
       }
-      send_raw_data();
+      //send_raw_data();
+      sendtoInfluxdb();
       bdata_is_rdy = false;
     }
-
-    /*
-      if (!client.connected()) {
+    if (!client.connected()) {
       syslogPayload = "failed, rc= ";
       syslogPayload += client.state();
       sendUdpSyslog(syslogPayload);
@@ -363,7 +399,7 @@
           lastReconnectAttempt = 0;
         }
       }
-      } else {
+    } else {
       if (bdoor_status != sensor_data.door) {
         doorpayload = "{\"DOOR\":";
         if ( sensor_data.door == 0 ) {
@@ -377,21 +413,14 @@
         bdoor_status = sensor_data.door;
       }

-      if (_salt != sensor_data._salt) {
-        payload = "{\"_salt\":";
-        payload += sensor_data._salt;
+      /*
+        if (_hash != sensor_data.hash) {
+        payload = "{\"hash\":";
+        payload += sensor_data.hash;
         payload += ",\"pls_no\":";
         payload += sensor_data.pls_no;
-        payload += ",\"pls_time\":";
-        payload += sensor_data.pls_wh;
-        payload += ",\"ct1\":";
-        payload += sensor_data.ct1_wh;
-        payload += ",\"ct2\":";
-        payload += sensor_data.ct2_wh;
-        payload += ",\"ct3\":";
-        payload += sensor_data.ct3_wh;
-        payload += ",\"powerAvg\":";
-        payload += (( sensor_data.ct2_wh + sensor_data.ct3_wh ) / 2) ;
+        payload += ",\"pls_ts\":";
+        payload += sensor_data.pls_ts;
         payload += ",\"FreeHeap\":";
         payload += ESP.getFreeHeap();
         payload += ",\"RSSI\":";
@@ -401,11 +430,12 @@
         payload += "}";

         sendmqttMsg(topic, payload);
-        _salt = sensor_data._salt;
-      }
+        _hash = sensor_data.hash;
+        }
+      */
       client.loop();
-      }
-    */
+    }
+
     ArduinoOTA.handle();
   } else {
     wifi_connect();


added calculateResult function

added calculateResult function

--- nerdigalli.ino
+++ nerdigalli.ino
@@ -96,5 +96,36 @@

 void calculateResult()
 {
+  boolean winner = 0;
+  int numberOfAs = 0;
+  int numberOfBs = 0;
+  int numberOfCs = 0;

+  for (int i = 0; i < displayString.length; i++) {
+    switch (displayString[i]) {
+        case 65:
+          numberOfAs++;
+          break;
+        case 66:
+          numberOfBs++;
+          break;
+        case 67:
+          numberOfCs++;
+          break;
+        default:
+          // do nothing
+    }
+  }
+
+  //
+  if (isRedOn == false &&
+      isGreenOn == true &&
+      (numberOfAs == 3 ||
+      numberOfBs == 3 ||
+      numberOfCs == 3 )) {
+
+    winner = 1;
+
+    displayResultMessage(winner);
+  }
 }


print count

print count

--- _56-gopro-control/a-91-config-on-rtc/a-91-config-on-rtc.ino
+++ _56-gopro-control/a-91-config-on-rtc/a-91-config-on-rtc.ino
@@ -1273,6 +1273,7 @@
     lcd.print("[P:3] put : ");

     int pre_progress = 0;
+    int count = 0;

     while (f.available()) {
       int c = f.readBytes(buff, ((len > sizeof(buff)) ? sizeof(buff) : len));
@@ -1305,7 +1306,11 @@
         return "0";
         break;
       }
-
+
+      lcd.setCursor(0, 2);
+      lcd.print("[P:3] : ");
+      lcd.print(count);
+      count++;
     }

     sslclient.print(content_last);
@@ -1335,6 +1340,7 @@
   if (ok == "0") {
   	lcd.setCursor(0, 2);
     lcd.print("[P:3] put err, reset");
+    delay(2000);
   	ESP.reset();
   }

@@ -1906,6 +1912,8 @@
       lcd.print("[P:1] get : ");

       int pre_progress = 0;
+      int count = 0;
+
       unsigned long dnstart = millis();

       while (http.connected() && (len > 0 || len == -1)) {
@@ -1930,15 +1938,20 @@
             len -= c;
           }
         }
+        lcd.setCursor(0, 2);
+        lcd.print("[P:1] : ");
+        lcd.print(count);
+        count++;
       }
       f.close();

       unsigned long dnstop = millis();
       float timestook = ( dnstop - dnstart ) / 1000 ;
       float dnspeed = rtc_boot_mode.gopro_size / (( dnstop - dnstart ) / 1000) ;
-
+
       lcd.setCursor(0, 2);
-      lcd.print("[P:1] ");
+      lcd.print("[P:1]              ");
+      lcd.setCursor(5, 2);
       lcd.print(dnspeed, 0);
       lcd.print(" K ");
       lcd.print(timestook, 1);
@@ -1998,7 +2011,7 @@
     if (gopro_poweron()) {
       lcd.setCursor(0, 2);
       lcd.print("---> OK");
-      delay(1000);
+      delay(3000);

       break;
     } else {


rtc_boot_mode.gopro_mode

rtc_boot_mode.gopro_mode

https://github.com/chaeplin/esp8266_and_arduino/issues/34

--- _56-gopro-control/a-91-config-on-rtc/a-91-config-on-rtc.ino
+++ _56-gopro-control/a-91-config-on-rtc/a-91-config-on-rtc.ino
@@ -233,7 +233,7 @@
   bool ok = system_rtc_mem_read(65, &rtc_boot_mode, sizeof(rtc_boot_mode));
   uint32_t hash = calc_hash(rtc_boot_mode);
   if (!ok || rtc_boot_mode.hash != hash) {
-    rtc_boot_mode.gopro_mode     = true;
+    rtc_boot_mode.gopro_mode     = false;
     rtc_boot_mode.formatspiffs   = false;
     rtc_boot_mode.Temperature    = 0;
     rtc_boot_mode.gopro_size     = 0;
@@ -768,7 +768,7 @@
     }
   }

-  if (!rtc_boot_mode.gopro_mode && rtc_boot_mode.attempt_this > 4) {
+  if (!rtc_boot_mode.gopro_mode || rtc_boot_mode.attempt_this > 4) {
     wifi_connect();
   } else {
     if ( rtc_boot_mode.twitter_phase > 1 ) {


Update 2018-Firefighter.ino

Update 2018-Firefighter.ino

--- 2018-Firefighter/2018-Firefighter.ino
+++ 2018-Firefighter/2018-Firefighter.ino
@@ -126,7 +126,7 @@
   } else {
     digitalWrite(BABY_LED, LOW);
   }
-  if(detetSound){
+  if(detectSound){
     digitalWrite(MIC_LED, HIGH);
   } else {
     digitalWrite(MIC_LED, LOW);


Initial extinguisher code

Initial extinguisher code

--- 2018-Firefighter/2018-Firefighter.ino
+++ 2018-Firefighter/2018-Firefighter.ino
@@ -10,6 +10,7 @@

 Servo leftServo;
 Servo rightServo;
+Servo extinguisher;

 Ultrasonic frontUltrasonic(FRONT_US_ECHO, FRONT_US_TRIG, true);

@@ -43,7 +44,7 @@
   leftServo.attach(LEFT_SERVO_PIN);
   rightServo.attach(RIGHT_SERVO_PIN);

-  // pinMode(5, OUTPUT);
+  pinMode(6, INPUT);
 }

 void loop() {
@@ -55,6 +56,24 @@
   } else {
     moveBackward();
   }
+
+  if (digitalRead(6)) {
+    moveForward();
+
+    if (frontUltrasonic.getDistance() > 3) {
+      moveForward();
+    } else {
+      stopRobot();
+      delay(500);
+
+      extinguisher.write(180);
+      delay(500);
+
+      if (!digitalRead(6)) {
+        extinguisher.write(90);
+      }
+    }
+  }

   delay(100);
 }


Added MQTT debug printing

Added MQTT debug printing

--- src/incubatorcontroller.ino
+++ src/incubatorcontroller.ino
@@ -73,6 +73,7 @@

 char server[] = IOT_ORG IOT_BASE_URL;
 char topic[] = "iot-2/evt/status/fmt/json";
+char debugTopic[] = "iot-2/evt/status/fmt/debug";
 char authMethod[] = "use-token-auth";
 char token[] = IOT_TOKEN;
 char clientId[] = "d:" IOT_ORG ":" IOT_DEVICE_TYPE ":" IOT_DEVICE_ID;
@@ -118,15 +119,18 @@

     ArduinoOTA.onStart([]() {
       Serial.println("Starting OTA update");
+      publishDebug("Starting OTA update");
     });
     ArduinoOTA.onEnd([]() {
       Serial.println("\nEnding OTA update");
+      publishDebug("Ending OTA update");
     });
     ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
       Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
     });
     ArduinoOTA.onError([](ota_error_t error) {
       Serial.printf("Error[%u]: ", error);
+      publishDebug("OTA Error");
       if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
       else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
       else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
@@ -162,6 +166,7 @@
   Serial.println("");
   Serial.print("WiFi connected with OTA4, IP address: ");
   Serial.println(WiFi.localIP());
+  publishDebug("WiFi Connected with OTA on IP: "+WiFi.localIP());

   configureOTA();
 }
@@ -183,16 +188,17 @@
   Serial.println();

   init_lcd();
-  lcd.print("Init v2");
-
+  lcd.print("Init v3");
+
+  init_wifi();
   // Start the DHT22
-
+  publishDebug("WiFi On");
+  publishDebug("Initialising Sensors");
   dht.begin();
   Serial.println("sensor is starting..");
   Serial.print("Reading Analog...");
   Serial.println(analogRead(0));
-
-  init_wifi();
+  publishDebug("Initialising Timers");
   initTimers();
 //----------------- wifi_set_sleep_type(LIGHT_SLEEP_T);
 //----------------- gpio_pin_wakeup_enable(GPIO_ID_PIN(2),GPIO_PIN_INTR_HILEVEL);
@@ -206,6 +212,7 @@
     isEnvironmentTimerComplete = false;

     Serial.println("Environment timer completed");
+    publishDebug("Environment timer completed");
     ++counter;
     readDHTSensor();
     connectWithBroker();
@@ -220,13 +227,16 @@
     isTrayTiltTimerComplete = false;

     Serial.println("Tray tilt timer completed");
+    publishDebug("Tray tilt time completed");
     //lcd.setCursor(0,2);
     lcd.setCursor(0,1);
     lcd.print("Tray tilting");
+    publishDebug("Tray tilting");
     delay(500);
     //lcd.setCursor(0,2);
     lcd.setCursor(0,1);
     lcdClearLine();
+    publishDebug("Tray tilting completed");

   }
   ArduinoOTA.handle();
@@ -254,6 +264,7 @@
   // Check if we fail to read from the DHT sensor
   if (isnan(h) || isnan(t)) {
     Serial.println("Failed to read from DHT sensor");
+    publishDebug("Failed to read from DHT sensor");
     //TODO: Do more here
   }

@@ -306,6 +317,19 @@
   }
 }

+void publishDebug(String debugMessage) {
+  String payload = "{\"d\":{\"myName\":\"ESP8266.Test1\",\"message\":";
+
+  payload += "\""+debugMessage+"\"}";
+
+  if (client.publish(debugTopic, (char *) payload.c_str())) {
+    Serial.println("Published debug OK");
+  } else {
+    Serial.print("Publish failed with error:");
+    Serial.println(client.state());
+  }
+}
+
 void displayLCD() {

   static char tempStr[15];
@@ -327,6 +351,7 @@
   lcd.print(firstLine);
   lcd.setCursor(0,1);
   lcd.print(secondLine);
+  publishDebug("Test message2");
 }

 void debugDisplayPayload() {