Tested and working

Tested and working

Waypoint system is fully functional. Still needs EEPROM support.

--- interrupt_driven_rgb.ino
+++ interrupt_driven_rgb.ino
@@ -11,15 +11,18 @@
 #include <LowPower_Teensy3.h>
 #include <FiniteStateMachine.h>

+// SPI Pins
 #define OLED_MOSI 11
 #define OLED_CLK 13
 #define OLED_CS 10
 #define OLED_DC 3
 #define OLED_RESET 2

+// Timer IDs
 #define GET_FIX_TIMER 1
 #define READ_LOCATION_TIMER 2

+// Index Labels
 #define LAT_INDEX 0
 #define LNG_INDEX 1

@@ -35,22 +38,23 @@
 const double waypoint[][2] = {
   { 36.049521, -95.921004 },
   { 36.048774, -95.921697 },
-  // { 36.140135, -96.004070 },
+  { 36.048706, -95.920835 },
 };

 Button button = Button(buttonPin);

-// U8GLIB_SSD1351_128X128_HICOLOR oled(OLED_CS, OLED_DC, OLED_RESET);
 Ucglib_SSD1351_18x128x128_HWSPI oled(OLED_DC, OLED_CS, OLED_RESET);

 TEENSY3_LP LP = TEENSY3_LP();

 TinyGPSPlus gps;

+// Custom NMEA parsers
 TinyGPSCustom ack_command(gps, "PMTK001", 1);
 TinyGPSCustom ack_response(gps, "PMTK001", 2);
 TinyGPSCustom awake(gps, "PMTK010", 1);

+// Internal States
 State GetFix       = State(enterGetFix, updateGetFix, exitGetFix);
 State ReadLocation = State(enterReadLocation, updateReadLocation, exitReadLocation);
 State SleepModules = State(enterSleepModules, updateSleepModules, NULL);
@@ -62,6 +66,7 @@

 FSM stateMachine = FSM(GetFix);

+// Event handlers
 void onClick(Button& button) {
   if(stateMachine.isInState(NextWaypoint)) {
     if(waypoint_index >= arraySize(waypoint)) {
@@ -107,23 +112,24 @@

 void enterGetFix() {
   drawTitle(F("Aquiring Fix"));
-  oled.setFont(ucg_font_fixed_v0r);
+  oled.setFont(ucg_font_6x12r);

   oled.setColor(255, 255, 0);
   oled.setPrintPos(0, oled.getHeight() / 2);
   oled << F("Please wait...");

+  delay(1000);
   TimedEvent.start(GET_FIX_TIMER);
 }

 void updateGetFix() {
-  if(gps.location.isValid())
+  if(gps.location.isValid() && gps.location.isUpdated() && gps.location.age() < 200)
     stateMachine.transitionTo(ReadLocation);

   oled.setColor(255, 255, 255);

   oled.setPrintPos(0, oled.getHeight() + oled.getFontDescent());
-  oled << gps.satellites.value() << F(" satellites");
+  oled.printf(F("%d satellites  "), gps.satellites.value());
 }

 void exitGetFix() {
@@ -132,7 +138,6 @@

 void enterReadLocation() {
   drawTitle(F("Directions"));
-  oled.setClipRange(0, 22, oled.getWidth(), oled.getHeight() - 22);

   TimedEvent.start(READ_LOCATION_TIMER);
 }
@@ -158,18 +163,6 @@
       stateMachine.transitionTo(NextWaypoint);
   }

-  if((gps.date.isUpdated() && gps.date.age() < 200) || (gps.time.isUpdated() && gps.time.age() < 200)) {
-    setTime(
-      gps.time.hour(),
-      gps.time.minute(),
-      gps.time.second(),
-      gps.date.day(),
-      gps.date.month(),
-      gps.date.year()
-    );
-    adjustTime(-6 * SECS_PER_HOUR);
-  }
-
   drawReadLocation();
 }

@@ -179,7 +172,7 @@

 void enterSleepModules() {
   drawTitle(F("Going to Sleep"));
-  oled.setFont(ucg_font_fixed_v0r);
+  oled.setFont(ucg_font_6x12r);

   oled.setColor(255, 255, 0);
   oled.setPrintPos(0, oled.getHeight() / 2);
@@ -205,7 +198,7 @@

 void enterWakeModules() {
   drawTitle(F("Waking"));
-  oled.setFont(ucg_font_fixed_v0r);
+  oled.setFont(ucg_font_6x12r);

   oled.setColor(255, 255, 0);
   oled.setPrintPos(0, oled.getHeight() / 2);
@@ -217,14 +210,13 @@
 void updateWakeModules() {
   if(awake.isUpdated()) {
     awake.value();
-    delay(1000);
     stateMachine.transitionTo(GetFix);
   }
 }

 void enterNextWaypoint() {
   drawTitle(F("Waypoint Reached"));
-  oled.setFont(ucg_font_fixed_v0r);
+  oled.setFont(ucg_font_6x12r);

   oled.setColor(255, 255, 0);
   oled.setPrintPos(0, oled.getHeight() / 2);
@@ -241,7 +233,7 @@

 void enterGPSFailure() {
   drawTitle(F("GPS Failure"));
-  oled.setFont(ucg_font_fixed_v0r);
+  oled.setFont(ucg_font_6x12r);

   oled.setColor(255, 255, 0);
   oled.setPrintPos(0, oled.getHeight() / 2);
@@ -249,45 +241,32 @@
 }

 void drawReadLocation() {
-  char datetime[24];
-  char status[24];
-
-  sprintf(datetime, "%d-%02d-%02d    %02d:%02d:%02d", year(), month(), day(), hourFormat12(), minute(), second());
-  sprintf(status, "%2d satellites", gps.satellites.value());
-
-  oled.setFont(ucg_font_7x13Br);
-
-  oled.setColor(0, 0, 255);
-  oled.drawRFrame(0, 0, oled.getWidth(), 20, 3);
-
-
+  // Distance as a formated string
+  char _distanceTo[14];
+  sprintf(_distanceTo, "%.2f mi\0", distanceTo);
+
+  // Debug info formatted
+  char _debug[21];
+  sprintf(_debug, "hdop: %d WP: %d/%d", gps.hdop.value(), (waypoint_index + 1), arraySize(waypoint));
+
+  oled.setFont(ucg_font_9x15Br);
+  oled.setColor(0, 255, 0);
+
+  oled.setPrintPos(0, oled.getHeight() / 2);
+  oled.printf(F("%-14s"), _distanceTo);
+
+  oled.setPrintPos(0, (oled.getHeight() / 2) + (oled.getFontAscent() - oled.getFontDescent()));
+  oled.printf(F("%-14s"), TinyGPSPlus::cardinal(course));
+
+  oled.setFont(ucg_font_6x12r);
   oled.setColor(255, 255, 255);
-  oled.setPrintPos(5, 15);
-  oled << F("Directions");
-
-  oled.setFont(ucg_font_fixed_v0r);
-
-  oled.setColor(255, 255, 255);
-  oled.setPrintPos(0, 22);
-  oled << datetime;
-
-  oled.setFont(ucg_font_7x13Br);
-  oled.setColor(0, 255, 0);
-
-  oled.setPrintPos(0, oled.getHeight() / 2);
-  oled << distanceTo << F(" miles");
-
-  oled.setPrintPos(0, (oled.getHeight() / 2) + (oled.getFontAscent() - oled.getFontDescent()));
-  oled << TinyGPSPlus::cardinal(course);
-
-  oled.setFont(ucg_font_fixed_v0r);
-  oled.setColor(255, 255, 255);

   oled.setPrintPos(0, oled.getHeight() + oled.getFontDescent());
-  oled << status;
-
-  oled.setPrintPos(0, oled.getHeight() + (oled.getFontDescent() + 12));
-  oled << F("hdop: ") << gps.hdop.value() << F(" WP: ") << (waypoint_index + 1) << '/' << arraySize(waypoint) << "    ";
+  oled.printf(F("%d satellites  "), gps.satellites.value());
+
+  // Debug info
+  oled.setPrintPos(0, (oled.getHeight() + oled.getFontDescent()) - 12);
+  oled.printf(F("%-21s"), _debug);
 }

 void setup() {
@@ -295,7 +274,7 @@
   button.holdHandler(onHold, 5000);

   TimedEvent.addTimer(GET_FIX_TIMER, 5000, gpsFailure);
-  TimedEvent.addTimer(READ_LOCATION_TIMER, 60000, initiateSleep);
+  TimedEvent.addTimer(READ_LOCATION_TIMER, 60000*5, initiateSleep);

   Serial3.begin(9600);
   delay(1000);
@@ -310,6 +289,6 @@
 void loop() {
   while(Serial3.available()) gps << Serial3.read();
   TimedEvent.loop();
-  Button.process();
+  button.process();
   stateMachine.update();
 }


Minor fixes, some indentation changes

Minor fixes, some indentation changes

--- FablightFirmware/FablightFirmware.ino
+++ FablightFirmware/FablightFirmware.ino
@@ -10,13 +10,14 @@

 void setup() {
 	initPWM();
-        fablight_ir_init();
+	fablight_ir_init();
 	Serial.begin(38400);
-        bt.begin(BT_BAUD);
-        setPWM(RED, 0);
-        setPWM(GREEN, 0);
-        setPWM(BLUE, 0);
-        setPWM(WHITE, 0);
+	bt.begin(BT_BAUD);
+
+	setPWM(RED, 0);
+	setPWM(GREEN, 0);
+	setPWM(BLUE, 0);
+	setPWM(WHITE, 0);
 }

 unsigned long startTime = 0;
@@ -32,9 +33,8 @@

 void loop() {
 	handle_bluetooth();
-        handle_ir();
+	handle_ir();
 	doAction();
-
 }

 void doAction() {
@@ -47,6 +47,7 @@
 				setPWM(i, (uint16_t)action[0].color[i]);
 				startColor[i] = action[0].color[i];
 			}
+			action[0] = action[1];
 			actionIndex = 0;
 		} else {
 			for(uint8_t i = 0; i < 4; i++) {
@@ -60,11 +61,11 @@
 			}
 		}
 	} else if(actionIndex == 1) {
-                if (action[0].relative) { // Relative change: Calculate new absolute before starting action
-                    for(uint8_t i = 0; i < 4; i++) {
+		if (action[0].relative) { // Relative change: Calculate new absolute before starting action
+			for(uint8_t i = 0; i < 4; i++) {
 		        action[0].color[i] += startColor[i];
 		    }
-                }
+		}
 		startTime = millis();
 		doing = 1;
 	}
@@ -75,10 +76,12 @@

 	while(bt.available()) {
 		char c = bt.read();
+		Serial.write(c);
 		if(c == '\r') {
-			if(index == sizeof(action[0]) * 2) {
-				actionIndex++;
+			if(index == 12) {
+				actionIndex |= 1;
 			}
+			Serial.write('\n');
 			bt.write('.');
 			index = 0;
 			continue;
@@ -97,9 +100,9 @@
 		case 2: action[actionIndex].fadeTime |= c <<  4; break;
 		case 3: action[actionIndex].fadeTime |= c; break;
 		case 4: case 6: case 8: case 10:
-			action[actionIndex].color[index/2 - 2] =  c << 4; break;
+			action[actionIndex].color[index/2 - 2] =  c << 8; break;
 		case 5: case 7: case 9: case 11:
-			action[actionIndex].color[index/2 - 2] |= c; break;
+			action[actionIndex].color[index/2 - 2] |= c << 4; break;
 		}
 		index++;
 	}


clean up code

clean up code

--- plant-monitor/plant-monitor.ino
+++ plant-monitor/plant-monitor.ino
@@ -44,18 +44,20 @@
 elapsedMillis lastPost;

 const unsigned int PUBLISHEVENT_TIME_HOUR = 15; // send events ~ 3pm
-boolean publishEvents = true;
+boolean particleEventPublished = true;

 void setup() {
   Serial.begin(9600);
   Time.zone(1);

+  // declare GPIO pins
   pinMode(led, OUTPUT);
   for (unsigned int i = 0; i < sizeof(soilSensors); i++) {
     pinMode(soilSensors[i].sensor, INPUT);
     pinMode(soilSensors[i].power, OUTPUT);
   }

+  // init BME280 sensor
   if (!bme.begin()) {
     Serial.println("Could not find a valid BME280 sensor, check wiring!");
     while (1);
@@ -68,6 +70,7 @@
   Particle.variable("soil1", &soil1, INT);
   Particle.variable("soil2", &soil2, INT);
   Particle.variable("soil3", &soil3, INT);
+  Particle.variable("status", &currentSensorStatus, INT);
 }

 void loop() {
@@ -91,12 +94,12 @@
           dumpSerial();

           // send events to particle cloud used to trigger IFTTT push notification
-          if (Time.hour() == PUBLISHEVENT_TIME_HOUR && publishEvents == true) {
+          if (Time.hour() == PUBLISHEVENT_TIME_HOUR && particleEventPublished == true) {
             postSoilEventToParticle();
-            publishEvents = false;
+            particleEventPublished = false; // only publish once
           }
           if (Time.hour() > PUBLISHEVENT_TIME_HOUR) {
-            publishEvents = true;
+            particleEventPublished = true; // reset publish status
           }
       }
     }
@@ -176,9 +179,8 @@
     return 1; // indicate temp increase above threshold
   } else if (tempDiff < 0){
     return 2; // indicate temp decrease above threshold
-  } else {
-    return 0; // indicate normal reading
-  }
+  }
+  return 0; // indicate normal reading
 }

 // read soil sensor data
@@ -195,10 +197,8 @@
       return 1; // indicate soil is to low
     } else if (soilValue > SOIL_THRESHOLD_HIGH) {
       return 2; // indicate soil is to high
-    } else {
-      return 0; // indicate normal reading
     }
-    return 0;
+    return 0; // indicate normal reading
 }

 void dumpSerial() {


Changes led controller

Changes led controller

--- arduino/led/led.ino
+++ arduino/led/led.ino
@@ -1,11 +1,12 @@
 int incomingByte = 0;
-int ledPin = 11;
+int ledPin = 13;
 String inString;
 int number;

 void setup(){
   Serial.begin(9600);
   pinMode(ledPin, OUTPUT);
+  analogWrite(ledPin, 0);
 }

 void send_numbers(){


Increased the size of local buffers to avoid buffer overflows. Cleaned some code comments.

--- ServerSketch/ServerSketch.ino
+++ ServerSketch/ServerSketch.ino
@@ -6,6 +6,9 @@
  For more information visit  : https://github.com/secondstory/LYT

  */
+
+// If debbuging declare
+#define DEBUG_CAT

 #include <Dhcp.h>
 #include <Dns.h>
@@ -34,7 +37,7 @@
 aJsonStream serial_stream(&Serial);

 // Web sockets
-#define WEB_SOCKET_BUFFER_SIZE 10000
+#define WEB_SOCKET_BUFFER_SIZE 30000

 // HW declaration
 #define TOTAL_NUM_Dx 14
@@ -57,6 +60,8 @@
 #define MESSAGES_PROCESSED_TOTAL_SIZE 1000
 #define PROCESSED_MESSAGE_ID_MAX_SIZE 100
 #define MAX_N_CLIENTS 100
+
+#define LOCAL_BUFFER_SIZE 1024

 class MessageManager
 {
@@ -158,10 +163,10 @@
     NULL, 0, 0, 0                                           }
 };

-/*
-This part of the code is inspired by the stock example coming with libsockets.
- Check it for more details.
- */
+
+//This part of the code is inspired by the stock example coming with libsockets.
+// Check it for more details.
+

 int force_exit = 0;
 enum lyt_protocols {
@@ -277,34 +282,41 @@
   {
     "/templates/play.html", "text/html"                                           }
   ,
-  /* last one is the default served if no match */
+  // last one is the default served if no match
   {
     "/index.html", "text/html"                                           }
   ,
 };

-/* this protocol server (always the first one) just knows how to do HTTP */
-
-/*
-This callback is called when the browser is refreshed (an HTTP call is performed).
- Here we send the files to the browser.
- */
+// this protocol server (always the first one) just knows how to do HTTP
+
+
+//This callback is called when the browser is refreshed (an HTTP call is performed).
+// Here we send the files to the browser.
 static int callback_http(struct libwebsocket_context *context,
 struct libwebsocket *wsi,
 enum libwebsocket_callback_reasons reason, void *user,
 void *in, size_t len)
 {
+
   //     Serial.println("callback_http()");
   // WE ARE ALWAYS HITTING THIS POINT

-  char buf[256];
+//  char buf[256];
+  char buf[LOCAL_BUFFER_SIZE];
+  memset(buf,'\0',LOCAL_BUFFER_SIZE);
   int n;

   switch (reason) {

   case LWS_CALLBACK_HTTP:
     lwsl_notice("LWS_CALLBACK_HTTP");
+
+
+ //     debug_serial_print("LWS_CALLBACK_HTTP: "); // debug
+//      debug_serial_println(String(reason)); // debug
+

     for (n = 0; n < (sizeof(whitelist) / sizeof(whitelist[0]) - 1); n++)
       if (in && strcmp((const char *)in, whitelist[n].urlpath) == 0)
@@ -313,23 +325,35 @@
     sprintf(buf, LOCAL_RESOURCE_PATH"%s", whitelist[n].urlpath);

     if (libwebsockets_serve_http_file(context, wsi, buf, whitelist[n].mimetype))
-      return 1; /* through completion or error, close the socket */
-
-    /*
-     * notice that the sending of the file completes asynchronously,
-     * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
-     * it's done
-     */
+      return 1; // through completion or error, close the socket
+
+     ///////////
+     // notice that the sending of the file completes asynchronously,
+     // we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
+     // it's done
+     ///////////

     break;

   case LWS_CALLBACK_HTTP_FILE_COMPLETION:

     lwsl_notice("LWS_FILE_COMPLETION");
+
+
+      // debug_serial_print("LWS_FILE_COMPLETION: "); // debug
+  //    debug_serial_println(String(reason)); // debug
+
+
     return 1;

   default:
+
+
+      // debug_serial_print("LWS_HTTP_CALLBACK_REASON: "); // debug
+ //     debug_serial_println(String(reason)); // debug
+
+
     break;
   }

@@ -339,7 +363,7 @@
 // Testing
 //char pcTestBuffer[512] = "{\"status\":OK,\"pins\":{\"14\":{\"label\":\"A0\",\"is_analog\":\"true\",\"is_input\":\"true\",\"value\":\"0.5\"},\"3\":{\"label\":\"PWM3\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.0\"}},\"connections\":[{\"source\":\"14\",\"target\":\"3\"}]}\"";

-/* lyt_protocol*/
+// CAT protocol
 static int
 callback_cat_protocol(struct libwebsocket_context *context,
 struct libwebsocket *wsi,
@@ -358,6 +382,11 @@

   case LWS_CALLBACK_SERVER_WRITEABLE:

+
+      // debug_serial_print("LWS_CALLBACK_SERVER_WRITEABLE: "); // debug
+  //    debug_serial_println(reason); // debug
+
+
     // **********************************
     // Send Galileo's HW state to ALL clients
     // This function is continuesly called
@@ -379,12 +408,22 @@
     // Process Data Receieved from the Website
     // Update Galileo's HW
     // **********************************
-//    procWebMsg((char*) in, len);
     processMessage((char*) in);

+
+      // debug_serial_print("LWS_CALLBACK_RECEIVE: "); // debug
+  //    debug_serial_println(reason); // debug
+
+
     break;

   default:
+
+
+      // debug_serial_print("LWS_PROTOCOL_REASON: "); // debug
+  //    debug_serial_println(reason); // debug
+
+
     break;
   }

@@ -395,35 +434,6 @@
 // Process recieved message from the webpage here....
 //------------------------------------------------------------
 void procClientMsg(char* _in, size_t _len) {
-
-  /*
-  {
-     "status": "<OK, ERROR>",
-     "pins": {
-        "<0,1,…,13,14,…,19>": {
-           "label": "<label text>",
-           "is_analog": <true,false>,
-           "is_input": <true,false>,
-           “input_min”: <0.0,1.0>,
-           "input_max": <0.0,1.0>,
-           “is_inverted”: <true,false>,
-           “is_visible”: <true,false>,
-           "value": <0.0,1.0>,
-           "is_timer_on": <true, false>,
-           "timer_value": <float>,
-           "damping": <0,9>,
-        }, ...,
-     },
-     "connections": [
-        {"source": "<0,1,…,13,14,…,19>",
-         "target": "<0,1,…,13,14…,19>"} ,
-          ...,
-     ]
-  }
-  */
-
-  //Serial.print//Serial.println("procClientMsg()");
-  //Serial.println(String(_in));

   // Create JSON message
   aJsonObject *pJsonMsg = aJson.parse(_in);
@@ -520,52 +530,17 @@
 // **********************************
 // Send pin status to the Website
 // **********************************
-/*
-int  sendStatusToWebsite(struct libwebsocket *wsi)
-{
-  int n;
-  unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 + LWS_SEND_BUFFER_POST_PADDING];
+int  sendStatusToWebsiteNew(struct libwebsocket *wsi)
+{
+
+  int n = 0;
+
+  unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + WEB_SOCKET_BUFFER_SIZE + LWS_SEND_BUFFER_POST_PADDING];
+  memset(buf,'\0',LWS_SEND_BUFFER_PRE_PADDING + WEB_SOCKET_BUFFER_SIZE + LWS_SEND_BUFFER_POST_PADDING);
   unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
-
-  n = sprintf((char *)p, "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%f,%f,%f,%f,%f,%f",
-  g_abD[0],
-  g_abD[1],
-  g_abD[2],
-  g_aiP[3],   // Px
-  g_abD[4],
-  g_aiP[5],   // Px
-  g_aiP[6],   // Px
-  g_abD[7],
-  g_abD[8],
-  g_aiP[9],   // Px
-  g_aiP[10],  // Px
-  g_aiP[11],  // Px
-  g_abD[12],
-  g_abD[13],
-  analogRead(A0)/float(ANALOG_IN_MAX_VALUE),
-  analogRead(A1)/float(ANALOG_IN_MAX_VALUE),
-  analogRead(A2)/float(ANALOG_IN_MAX_VALUE),
-  analogRead(A3)/float(ANALOG_IN_MAX_VALUE),
-  analogRead(A4)/float(ANALOG_IN_MAX_VALUE),
-  analogRead(A5)/float(ANALOG_IN_MAX_VALUE)
-    );
-
-  n = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
-
-  return n;
-}
-*/
-
-int  sendStatusToWebsiteNew(struct libwebsocket *wsi)
-{
-
-  int n = 0;
-
-  unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + WEB_SOCKET_BUFFER_SIZE + LWS_SEND_BUFFER_POST_PADDING];
-  unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];

   updateBoardState();
-
+
   aJsonObject *msg = getJsonBoardState();

   aJsonStringStream stringStream(NULL, (char *)p, WEB_SOCKET_BUFFER_SIZE);
@@ -582,15 +557,15 @@
   return n;
 }

-/* list of supported protocols and callbacks */
+// list of supported protocols and callbacks
 static struct libwebsocket_protocols protocols[] = {
-  /* first protocol must always be HTTP handler, to serve webpage */
-
-  {
-    "http-only",		/* name */
-    callback_http,		/* callback */
-    0,			/* per_session_data_size */
-    0,			/* max frame size / rx buffer */
+  // first protocol must always be HTTP handler, to serve webpage
+
+  {
+    "http-only",		// name */
+    callback_http,		// callback */
+    0,			// per_session_data_size */
+    0,			// max frame size / rx buffer */
   }
   , // manages data in and data out from and to the website
   {
@@ -602,7 +577,7 @@
   ,

   {
-    NULL, NULL, 0, 0                                           } /* terminator */
+    NULL, NULL, 0, 0                                           } // terminator */
 };

 void sighandler(int sig)
@@ -629,11 +604,11 @@
   signal(SIGINT, sighandler);
   int syslog_options =  LOG_PID | LOG_PERROR;

-  /* we will only try to log things according to our debug_level */
+  // we will only try to log things according to our debug_level */
   setlogmask(LOG_UPTO (LOG_DEBUG));
   openlog("lwsts", syslog_options, LOG_DAEMON);

-  /* tell the library what debug level to emit and to send it to syslog */
+  // tell the library what debug level to emit and to send it to syslog */
   lws_set_log_level(debug_level, lwsl_emit_syslog);

   info.iface = iface;
@@ -684,7 +659,8 @@
   // Initialize all pins with no lable and 0.0 value
   for(int i=0; i<TOTAL_NUM_OF_PINS; i++)
   {
-    memset(g_aPins[i].label, '\0', sizeof(g_aPins[i].label));
+//    memset(g_aPins[i].label, '\0', sizeof(g_aPins[i].label));
+    memset(g_aPins[i].label, '\0', PIN_LABEL_SIZE);
     strcpy(g_aPins[i].label,"");

     g_aPins[i].input_min = 0.0;
@@ -704,7 +680,8 @@
     g_aPins[i].prev_damping = 0;

     // Set pin connections
-    memset(g_aPins[i].connections, '\0', sizeof(g_aPins[i].connections));
+//    memset(g_aPins[i].connections, '\0', sizeof(g_aPins[i].connections));
+    memset(g_aPins[i].connections, '\0', TOTAL_NUM_OF_PINS);
     for(int j=0; j<TOTAL_NUM_OF_PINS; j++)
     {
       if( i == j ) // Pins are always connected to themselves
@@ -871,57 +848,8 @@
 //Serial.print("fFiltered: "); //Serial.println(fFiltered);
 //Serial.print("Value: "); Serial.println(g_aPins[_iInPinNum].value);

-
-  /*
-  // Check if the damping value has changed
-  if( g_aPins[_iInPinNum].damping != g_aPins[_iInPinNum].prev_damping )
-  {
-    // Clear the history values
-    for(int i=0; i<TOTAL_NUM_OF_PAST_VALUES; i++)
-      g_aPins[_iInPinNum].past_values[i] = 0.0;
-  }
-
-  g_aPins[_iInPinNum].damping
-
-  g_aPins[_iInPinNum].value
-  g_aPins[_iInPinNum].prev_value
- */
   return fFiltered;
 }
-
-/*
-float getFilteredPinValue(int _iInPinNum)
-{
-  // Check if the damping value has changed
-  if( g_aPins[_iInPinNum].damping != g_aPins[_iInPinNum].prev_damping )
-  {
-    // Clear the history values
-    for(int i=0; i<TOTAL_NUM_OF_PAST_VALUES; i++)
-      g_aPins[_iInPinNum].past_values[i] = 0.0;
-  }
-
-  // Update
-  g_aPins[_iInPinNum].prev_damping =   g_aPins[_iInPinNum].damping;
-
-  // Update tap value
-//  float fFilterTab = 1.0/(g_aPins[_iInPinNum].damping+1); // The sampling rate is so slow this filter can see it.
-  float fFilterTab = 1.0/(g_aPins[_iInPinNum].damping*100+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*100; i++)
-      fMultAndAccum += fFilterTab*g_aPins[_iInPinNum].past_values[i];
-  Serial.print("MultAndAccum: "); Serial.println(fMultAndAccum);
-  return fMultAndAccum;
-}
-*/

 ////////////////////////////////////////////////
 // Get the board state and return a JSON object
@@ -933,7 +861,8 @@

    g_iMsgCount++; // debug

-  char buff[100];
+//  char buf[LOCAL_BUFFER_SIZE];
+//  memset(buf,'\0',LOCAL_BUFFER_SIZE);

   aJsonObject* poJsonBoardState = aJson.createObject();

@@ -959,7 +888,9 @@

   // Create PINS
   int iaPinConnects[TOTAL_NUM_OF_PINS];
-  char caPinNumBuffer[10];
+  char caPinNumBuffer[LOCAL_BUFFER_SIZE];
+  memset(caPinNumBuffer,'\0',LOCAL_BUFFER_SIZE);
+
   for(int i=0; i<TOTAL_NUM_OF_PINS ;i++)
   {
     aJson.addItemToObject(apoPin[i],"label", aJson.createItem( g_aPins[i].label ) );
@@ -1033,19 +964,7 @@
     aJson.addItemToObject(poPins,caPinNumBuffer,apoPin[i]);

   }
-
-  /*
-  {"status":<OK,ERROR>,  "pins":{"<0,1,…,13,A0,…,A5>":  {
-  "label":"<label text>",
-	"is_analog":"<true,false>",
-	"is_input":"<true,false>",
-“sensitivity”:”<0.0,1.0>”,
-“is_inverted”:”<true,false>”,
-“is_visible”:”<true,false>”,
-"value":"<0.0,1.0>",  },  ...,  },
-"connections":[ {"source":"<0,1,…,13,A0,…,A5>","target":"<0,1,…,13,A0,…,A5>",”is_connected”:”<true,false>”},  ...,  ]  }
-  */
-
+
   // Create CONNECTIONS
   for(int i=0; i<TOTAL_NUM_OF_PINS ;i++)
   {
@@ -1094,6 +1013,17 @@
 //  Serial.print("Msg recvd: ");
 //  Serial.println(_acMsg);

+  debug_serial_print("Msg received. Size: ");
+//  debug_serial_println(sizeof(_acMsg));
+    #ifdef DEBUG_CAT
+      Serial.println(strlen(_acMsg)); // debug
+    #endif
+  debug_serial_print(_acMsg);
+
+  // Ignore messages bigger than we can handle
+  if( sizeof(_acMsg) >= WEB_SOCKET_BUFFER_SIZE )
+    return;
+
   aJsonObject *poMsg = aJson.parse(_acMsg);

   if(poMsg != NULL)
@@ -1156,12 +1086,12 @@
   // Iterate all pins and check if we have data available
   for(int i=0; i<TOTAL_NUM_OF_PINS; i++)
   {
-    char pinstr[3];
+    char pinstr[10];
     snprintf(pinstr, sizeof(pinstr), "%d", i);
     aJsonObject *poPinVals = aJson.getObjectItem(_pJsonPins, pinstr);
     if (poPinVals)
     {
-      char sPinState[128];
+      char sPinState[LOCAL_BUFFER_SIZE];

       aJsonObject *poLabel = aJson.getObjectItem(poPinVals, "label");
       if (poLabel)
@@ -1315,14 +1245,14 @@
         break;
       }
     }
-    /*
-    Serial.print("Source: ");
-    Serial.println(String(uiSourcePin));
-    Serial.print("Target: ");
-    Serial.println(String(uiTargetPin));
-    Serial.print("Connect: ");
-    Serial.println(String(uiTargetPin));
-    */
+
+ //   Serial.print("Source: ");
+ //   Serial.println(String(uiSourcePin));
+//    Serial.print("Target: ");
+//    Serial.println(String(uiTargetPin));
+//    Serial.print("Connect: ");
+//    Serial.println(String(uiTargetPin));
+
   }
 }

@@ -1333,12 +1263,10 @@
 {
   // put your setup code here, to run once:
   Serial.begin(9600);
+
+
   //Serial.println("Starting WebServer");
   system("/home/root/startAP");
-
-  // Initilize data structures to control client/server protocol
-  //Serial.println("Initilzie Client/Server protocol");
-  //initCommProtocol();

   // Initialize HW and JSON protocol code
   //Serial.println("Initilize Hardware");
@@ -1348,17 +1276,7 @@
   initWebsocket();

 }
-/*
-char g_acMessage[1000];
-int g_ToggleFlag = 0;
-char g_acPin3_On[] = "{\"status\":\"OK\",\"pins\":{ \"13\":{\"label\":\"Pin 13\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"2\":{\"label\":\"Pin 2\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"4\":{\"label\":\"Pin 4\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"7\":{\"label\":\"Pin 7\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"8\":{\"label\":\"Pin 8\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"12\":{\"label\":\"Pin 12\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"3\":{\"label\":\"Pin 3\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"5\":{\"label\":\"Pin 5\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"6\":{\"label\":\"Pin 6\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"9\":{\"label\":\"Pin 9\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"10\":{\"label\":\"Pin 10\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"11\":{\"label\":\"Pin 11\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}   }}";
-char g_acPin3_Off[] = "{\"status\":\"OK\",\"pins\":{ \"13\":{\"label\":\"Pin 13\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"0\"}, \"2\":{\"label\":\"Pin 2\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"0\"}, \"4\":{\"label\":\"Pin 4\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"0\"}, \"7\":{\"label\":\"Pin 7\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"0\"}, \"8\":{\"label\":\"Pin 8\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"0\"}, \"12\":{\"label\":\"Pin 12\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"0\"}, \"3\":{\"label\":\"Pin 3\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.1\"}, \"5\":{\"label\":\"Pin 5\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.1\"}, \"6\":{\"label\":\"Pin 6\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.1\"}, \"9\":{\"label\":\"Pin 9\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.1\"}, \"10\":{\"label\":\"Pin 10\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.1\"}, \"11\":{\"label\":\"Pin 11\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.1\"}   }}";
-//char g_acConnA0_TO_3[] = "{\"status\":\"OK\",\"connections\":[{\"source\":\"14\",\"target\":\"3\"},{\"source\":\"15\",\"target\":\"5\"}]}";
-
-char g_acPin13_On_3_Analog[] = "{\"status\":\"OK\",\"pins\":{ \"13\":{\"label\":\"Pin 13\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"3\":{\"label\":\"Pin 3\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.0\"}  }}";
-char g_acConnA0_TO_3[] = "{\"status\":\"OK\",\"connections\":[{\"source\":\"14\",\"target\":\"3\"},{\"source\":\"15\",\"target\":\"3\"}]}";
-int g_iDebugState = 0;
-*/
+
 unsigned long last_print = 0;

 void loop()
@@ -1368,38 +1286,10 @@

     ///////////////////////////////////////
     // Connect/Disconnect
-    /*
-    switch(g_iDebugState)
-    {
-      case 0:
-        snprintf(g_acMessage,sizeof(g_acMessage),g_acPin13_On_3_Analog);
-        processMessage(g_acMessage);
-        g_iDebugState = 1;
-      break;
-
-      case 1:
-        snprintf(g_acMessage,sizeof(g_acMessage),g_acConnA0_TO_3);
-        processMessage(g_acMessage);
-        g_iDebugState = 2;
-      break;
-
-      default:
-
-      break;
-    }
-
-    updateBoardState();
-    */
     ///////////////////////////////////////
-
+    Serial.println("LOOP(7)");
     //////////////////////////////////////////
     // Test sending message
-    /*
-    aJsonObject *msg = getJsonBoardState();
-    aJson.print(msg, &serial_stream);
-    Serial.println("");
-    aJson.deleteItem(msg);
-    */
     //////////////////////////////////////////

     last_print = millis();
@@ -1430,3 +1320,20 @@
     }
   }
 }
+
+/////////////////////////////////////////////////////////////////////////////////
+// Other tools
+/////////////////////////////////////////////////////////////////////////////////
+void debug_serial_print(char* _sString)
+{
+    #ifdef DEBUG_CAT
+      Serial.print(_sString); // debug
+    #endif
+}
+
+void debug_serial_println(char* _sString)
+{
+    #ifdef DEBUG_CAT
+      Serial.println(_sString); // debug
+    #endif
+}


Disable debug mode for our production build

Debug mode drastically slows down the video selection mode, because it
sends updates to the serial console as it switches between each video
(and pressing the button to change the most significant light moves up
to 64 videos at a time).

--- Arduino/LightPlayer/LightPlayer.ino
+++ Arduino/LightPlayer/LightPlayer.ino
@@ -2,7 +2,7 @@
 #include <SdFat.h>
 #include <FAB_LED.h>

-#define DEBUG
+//#define DEBUG

 enum {
   SD_CHIP_SELECT = 4,


Smoother pan/tilt servo movement and more explicit logging.

--- Arduino/Thingamabot/Thingamabot.ino
+++ Arduino/Thingamabot/Thingamabot.ino
@@ -261,18 +261,48 @@
 // "angle" is a value from 0 to 160 (eventually 180), in degrees, except that 999 indicates return to home position
 void set_servo(int servoID, int angle)
 {
-
+    int index;
+
     if (angle == 999) {
         pan_servo.write(90);
         tilt_servo.write(90);
+        log(F("Camera servos reset to home:"), index);
     }
     else if (servoID == PAN_SERVO) {
-        pan_servo.write(angle);
-        log(F("Set pan servo to:"), angle);
+        index = pan_servo.read();
+        if (index > angle) {
+            for (index; index >= angle; index--) {
+                pan_servo.write(index);
+                delay(15);
+          }
+          log(F("Set pan servo to:"), pan_servo.read());
+        }
+        else if (index < angle) {
+            for (index; index <= angle; index++) {
+                pan_servo.write(index);
+                delay(15);
+           }
+           log(F("Set pan servo to:"), pan_servo.read());
+        }
+      else log(F("Pan servo already set to:"), pan_servo.read());
     }
     else if (servoID == TILT_SERVO) {
-        tilt_servo.write(angle);
-        log(F("Set tilt servo to:"), angle);
+        index = tilt_servo.read();
+        if (index > angle) {
+            for (index; index >= angle; index--) {
+                tilt_servo.write(index);
+                delay(15);
+            }
+            log(F("Set tilt servo to:"), tilt_servo.read());
+        }
+        else if (index < angle) {
+            for (index; index <= angle; index++) {
+                tilt_servo.write(index);
+                delay(15);
+            }
+            log(F("Set tilt servo to:"), tilt_servo.read());
+        }
+      else log(F("Tilt servo already set to:"), tilt_servo.read());
     }
 }


Delete SpireTest.ino

Delete SpireTest.ino

--- Charliecube/SpireTest/SpireTest.ino
+++ Charliecube/SpireTest/SpireTest.ino
@@ -1,80 +0,0 @@
-//CharlieCube Spire Test Program
-
-#define PIN_A 3
-#define PIN_B 4
-#define PIN_C 6
-#define PIN_D 5
-int delayTime = 300;
-
-void setup()
-{
-// first set all pins to input, or high impedance
-// (not strictly necessary as all pins are inputs by default)
-pinMode(PIN_A, INPUT);
-pinMode(PIN_B, INPUT);
-pinMode(PIN_C, INPUT);
-pinMode(PIN_C, INPUT);
-}
-
-void loop()
-{
-
-set_pins(PIN_B, PIN_A);
-delay(delayTime);
-set_pins(PIN_C, PIN_A);
-delay(delayTime);
-set_pins(PIN_D, PIN_A);
-delay(delayTime);
-
-set_pins(PIN_C, PIN_B);
-delay(delayTime);
-set_pins(PIN_D, PIN_B);
-delay(delayTime);
-set_pins(PIN_A, PIN_B);
-delay(delayTime);
-
-set_pins(PIN_D, PIN_C);
-delay(delayTime);
-set_pins(PIN_A, PIN_C);
-delay(delayTime);
-set_pins(PIN_B, PIN_C);
-delay(delayTime);
-
-set_pins(PIN_A, PIN_D);
-delay(delayTime);
-set_pins(PIN_B, PIN_D);
-delay(delayTime);
-set_pins(PIN_C, PIN_D);
-delay(delayTime);
-
-
-
-}
-
-void set_pins(int low_pin, int high_pin)
-{
-// reset all the pins
-reset_pins();
-
-// set the high and low pins to output
-pinMode(high_pin, OUTPUT);
-pinMode(low_pin, OUTPUT);
-
-// set high pin to logic high, low to logic low
-digitalWrite(high_pin, HIGH);
-digitalWrite(low_pin,LOW);
-}
-
-void reset_pins()
-{
-// start by ensuring all pins are at input and low
-pinMode(PIN_A, INPUT);
-pinMode(PIN_B, INPUT);
-pinMode(PIN_C, INPUT);
-pinMode(PIN_D, INPUT);
-
-digitalWrite(PIN_A, LOW);
-digitalWrite(PIN_B, LOW);
-digitalWrite(PIN_C, LOW);
-digitalWrite(PIN_D, LOW);
-}


Removed fullKeyboard check as no longer needed

--- ZXKBFirmware/ZXKBFirmware.ino
+++ ZXKBFirmware/ZXKBFirmware.ino
@@ -17,13 +17,8 @@
 // we can release them correctly without constantly sending Keyboard.release commands for those keys
 bool symbolShiftPressed = false;
 bool capsShiftPressed = false;
-
+bool keyboardModeButtonPressed = false;
 bool debug = false;
-
-// simply disables all keyboard functions apart from switching keyboard mode. Used during testing
-bool fullKeyboard = true;
-
-bool keyboardModeButtonPressed = false;

 enum {
   MODE_SPECTRUM = 1,
@@ -174,8 +169,6 @@
     }
   }

-  if (!fullKeyboard) return;
-
   // Loop through all the address lines
   for (int addrLine = 0; addrLine < addressLines; addrLine++) {


Cleanup

Cleanup

--- examples/Pins/CosaGPIO/CosaGPIO.ino
+++ examples/Pins/CosaGPIO/CosaGPIO.ino
@@ -32,7 +32,7 @@
 void setup()
 {
   uart.begin(9600);
-  trace.begin(&uart, PSTR("CosaPIO: started"));
+  trace.begin(&uart, PSTR("CosaGPIO: started"));
   Watchdog::begin();
   TRACE(led.mode());
   TRACE(button.mode());


Fix another compiler directive

Fix another compiler directive

to compile ATMEGA328

--- examples/RF12/RF12demo/RF12demo.ino
+++ examples/RF12/RF12demo/RF12demo.ino
@@ -973,11 +973,11 @@
           Sleepy::powerDown();
 }

-#if defined(__AVR_ATtiny84__) || not defined(__AVR_ATtiny44__)
+#if defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny44__)
 ttyIn InChar =  ttyIn(10); // PA0 in Tiny84
 #endif
 void setup() {
-#if defined(__AVR_ATtiny84__) || not defined(__AVR_ATtiny44__)
+#if defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny44__)
   delay(1000);        // Delay on startup to avoid ISP/RFM12B interference.
   InChar.begin();        // ttyIn code is set up for 16MHz processor and we are 8MHz
 #endif


cleanup, resolves #432 - other than nodes/postings stuff


Clean up spacing a bit

Clean up spacing a bit

--- ARTF_Sensors/examples/LowPowerUltrasonicWithSD/LowPowerUltrasonicWithSD.ino
+++ ARTF_Sensors/examples/LowPowerUltrasonicWithSD/LowPowerUltrasonicWithSD.ino
@@ -50,9 +50,9 @@
   output += "Trial " + String(count) + "\n";
   output += "-------------------\n";

+
   digitalWrite(MOSFET_US_PIN, HIGH);
   delay(3000);
-

   // Take X readings
   int distanceReadings[NUM_READINGS];
@@ -69,6 +69,7 @@
   digitalWrite(MOSFET_US_PIN, LOW);
   delay(500);

+
   // Average the readings
   double sumDistance = 0.0;
   for (int i = 0; i < NUM_READINGS; ++i)
@@ -82,9 +83,6 @@

   output += "Rounded:" + String(roundedDistance) + "\n\n";

-
-
-
   sd.begin();
   sd.writeFile(OUTPUT_FILENAME, output);


Fix HCS on reading data from server

Fix HCS on reading data from server

--- BiotechHardware/hcs/hcs.ino
+++ BiotechHardware/hcs/hcs.ino
@@ -1,11 +1,11 @@
 #include <SPI.h>
-#include <HttpClient.h>
 #include <Ethernet.h>
 #include <EthernetClient.h>
+#include <HttpClient.h>

 byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xF5, 0x30 };
-const char hostname[] = "192.168.1.3";
-IPAddress ip(192,168,4,3);
+const char hostname[] = "192.168.2.4";
+IPAddress ip(192,168,1,6);

 int commaPosition;
 String lamp1_val;
@@ -15,17 +15,21 @@

 const int lamp1_pin = 2;
 const int lamp2_pin = 3;
-const int lamp3_pin = 4;
-const int lamp4_pin = 5;
-const int led_power = A5;
+const int lamp3_pin = 5;
+const int lamp4_pin = 6;
+/*const int led_power = A5;
 const int lamp1_power = A4;
 const int lamp2_power = A3;
 const int lamp3_power = A2;
-const int lamp4_power = A1;
+const int lamp4_power = A1;*/

 void setup(){
   Serial.begin(9600);
+  Serial.println("Start");
   Ethernet.begin(mac, ip);
+
+  Serial.println(Ethernet.localIP());
+
   pinMode(lamp1_pin, OUTPUT);
   pinMode(lamp2_pin, OUTPUT);
   pinMode(lamp3_pin, OUTPUT);
@@ -35,25 +39,24 @@
   pinMode(lamp2_power, OUTPUT);
   pinMode(lamp3_power, OUTPUT);
   pinMode(lamp4_power, OUTPUT);
-  digitalWrite(lamp1_pin, HIGH);
+ /* digitalWrite(lamp1_pin, HIGH);
   digitalWrite(lamp2_pin, HIGH);
   digitalWrite(lamp3_pin, HIGH);
   digitalWrite(lamp4_pin, HIGH);
-  digitalWrite(led_power, HIGH);
+  digitalWrite(led_power, HIGH);*/
   digitalWrite(lamp1_power, LOW);
   digitalWrite(lamp2_power, LOW);
   digitalWrite(lamp3_power, LOW);
   digitalWrite(lamp4_power, LOW);
   delay(1000);
-  Serial.println("Dimas Ganteng");
 }

 void loop(){
-  String val = get_lamp("/api/hcs_get_lamp");
+  String val = get_lamp("/api/hcs/hcs_get_lamp");
   Serial.println(val);

   commaPosition = val.indexOf(';');
-  lamp1_val = val.substring(0,commaPosition);
+  lamp1_val = val.substring(1,commaPosition);
   val = val.substring(commaPosition+1, val.length());
   Serial.println(lamp1_val);

@@ -66,7 +69,7 @@
   lamp3_val = val.substring(0,commaPosition);
   Serial.println(lamp3_val);

-  lamp4_val = val.substring(commaPosition+1, val.length());
+  lamp4_val = val.substring(commaPosition+1, (val.length()-1));
   Serial.println(lamp4_val);

   if(lamp1_val == "1"){


Ooops

Ooops

--- arduino/src/stolenmeeting.ino
+++ arduino/src/stolenmeeting.ino
@@ -4,8 +4,8 @@
 #include <SoftTimer.h>

 String ID = "1D";
-String SSID = "______$$";
-String PASS = "luk4zush4r3";
+String SSID = "";
+String PASS = "";

 int SERVER_PORT = 5000;
 String SERVER_ADDRESS = "192.168.23.104";


Increased delay.

Increased delay.

--- arduino_code/arduino_code.ino
+++ arduino_code/arduino_code.ino
@@ -19,7 +19,7 @@
 void loop()
 {
   printTemp();
-  delay(50);
+  delay(500);
   printDHT();
   delay(500);
 }


speed conversion fixed

speed conversion fixed

--- ROD.ino
+++ ROD.ino
@@ -28,7 +28,11 @@

   void loop() {
+    int x;
+    int y;
+    x = y = input();
     drive();//continuously drive motor
+
     Serial.println(i);
   }
   void drive(int x, int y)//sends control signal to motor shield
@@ -37,9 +41,7 @@
     int speed1;//speed right motor
     int direction0 = CW; //direction left motor
     int direction1 = CW; //direction right motor
-    calcultateSpeedDirection (x, y);//calculate parameters
-    speed0 = map(velocityLeft, 0, controllerMax, 0, 255);
-    speed1 = map(velocityRight, 0, controllerMax, 0, 255);
+    calcultateSpeedDirection (x, y, &speed0, &speed1, &direction0, &direction1); //calculate parameters
     adjustMotor(0, direction0, speed0);//run left motor
     adjustMotor (1, direction1, speed1);//run right motor
   }
@@ -55,16 +57,18 @@
       digitalWrite(inBpin[motor], LOW);
     analogWrite(pwmpin[motor], pwm);
   }
-  void calcultateSpeedDirection (x, y)//converts input in controller-format to suitable combination of track movements
+  void calcultateSpeedDirection (int x, int y, int *vL, int *vR, int *dL, int *dR) //converts input in controller-format to suitable combination of track movements
   {
-    int velocityLeft = (x / 2) + y;//compute velociy left track
-    if (velocityLeft < 0)// if needed change left direction
+    *vL = (x / 2) + y;//compute velociy left track
+    if (*vL < 0)// if needed change left direction
     {
-      directionLeft = CCW;
+      *dL = CCW;
     }
-    int velocityRight = ((-x) / 2) + y;//see Left
-    if (velocityRight < 0)
+    *vR = ((-x) / 2) + y;//see Left
+    if (*vR < 0)
     {
-      directionRight = CCW;//see Left
+      *dR = CCW;//see Left
     }
+    *vL = map(*vL, 0, controllerMax, 0, 255);
+    *vR = map(*vR, 0, controllerMax, 0, 255);
   }


Test routine: Added pin 13 LED test

Test routine: Added pin 13 LED test

--- examples/TestRoutine/TestRoutine.ino
+++ examples/TestRoutine/TestRoutine.ino
@@ -95,6 +95,10 @@
     PHN_Settings_Save(SETTINGS_DEFAULT);
   }

+  // Turn on LED Pin 13
+  pinMode(13, OUTPUT);
+  digitalWrite(13, LOW);
+
   // LCD Test
   startLCDTest();

@@ -184,4 +188,4 @@

   // Wipe screen
   display.fill(BLACK);
-}+}


added more comments

added more comments

--- Modules/Modifier/Counter/ArduinoCodes/CounterATtiny/CounterATtiny.ino
+++ Modules/Modifier/Counter/ArduinoCodes/CounterATtiny/CounterATtiny.ino
@@ -25,6 +25,7 @@
 #include <SignalProcessing.h>

 #define THRESH_LOW 300          //any ADC value below this will be considered LOW
+#define THRESH_HIGH 700         //any ADC value above this will be considered HIGH

 int input_pin = 3;                           //Pin 2 on ATtiny
 int output_pin = 1;                          //Pin 6 on ATtiny


WDRC_FIR_8Band: fix Travis errors?

WDRC_FIR_8Band: fix Travis errors?

--- examples/03-Intermediate/WDRC_FIR_8Band/WDRC_FIR_8Band.ino
+++ examples/03-Intermediate/WDRC_FIR_8Band/WDRC_FIR_8Band.ino
@@ -21,7 +21,6 @@

 //Use test tone as input (set to 1)?  Or, use live audio (set to zero)
 #define USE_TEST_TONE_INPUT 0
-

 // Include all the of the needed libraries
 #include <Tympan_Library.h>
@@ -38,12 +37,12 @@
 AudioOutputI2S_F32          i2s_out(audio_settings);        //Digital audio *to* the Teensy Audio Board DAC.  Expects Int16.  Stereo

 //create audio objects for the algorithm
-AudioEffectGain_F32     preGain;
-#define N_CHAN 8        //number of channels to use for multi-band compression
-AudioFilterFIR_F32      firFilt[N_CHAN];  //here are the filters to break up the audio into multipel bands
+#define N_CHAN 8         //number of channels to use for multi-band compression
+AudioEffectGain_F32      preGain;
+AudioFilterFIR_F32       firFilt[N_CHAN];  //here are the filters to break up the audio into multipel bands
 AudioEffectCompWDRC_F32  compPerBand[N_CHAN]; //here are the per-band compressors
 AudioEffectCompWDRC_F32  compBroadband; //here is the broad band compressors
-AudioMixer8_F32         mixer1; //mixer to reconstruct the broadband audio
+AudioMixer8_F32          mixer1; //mixer to reconstruct the broadband audio

 //choose the input audio source
 #if (USE_TEST_TONE_INPUT == 1)
@@ -82,7 +81,6 @@
 AudioConnection_F32     patchCord36(compPerBand[5], 0, mixer1, 5);
 AudioConnection_F32     patchCord37(compPerBand[6], 0, mixer1, 6);
 AudioConnection_F32     patchCord38(compPerBand[7], 0, mixer1, 7);
-

 //connect the output of the mixers to the final broadband compressor
 AudioConnection_F32     patchCord43(mixer1, 0, compBroadband, 0);
@@ -118,6 +116,63 @@
   myTympan.setInputGain_dB(15.f); // set MICPGA volume, 0-47.5dB in 0.5dB setps
 }

+
+static void configureBroadbandWDRCs(float fs_Hz, BTNRH_WDRC::CHA_WDRC *gha, AudioEffectCompWDRC_F32 *WDRC) {
+  //logic and values are extracted from from CHAPRO repo agc_prepare.c...the part setting CHA_DVAR
+
+  //extract the parameters
+  float atk = (float)gha->attack;  //milliseconds!
+  float rel = (float)gha->release; //milliseconds!
+  //float fs = gha->fs;
+  float fs = (float)fs_Hz; // WEA override...not taken from gha
+  float maxdB = (float) gha->maxdB;
+  float exp_cr = (float)gha->exp_cr;
+  float exp_end_knee = (float)gha->exp_end_knee;
+  float tk = (float) gha->tk;
+  float comp_ratio = (float) gha->cr;
+  float tkgain = (float) gha->tkgain;
+  float bolt = (float) gha->bolt;
+
+  //set the compressor's parameters
+  WDRC->setSampleRate_Hz(fs);
+  WDRC->setParams(atk,rel,maxdB,exp_cr,exp_end_knee,tkgain,comp_ratio,tk,bolt);
+
+}
+
+static void configurePerBandWDRCs(int nchan, float fs_Hz, BTNRH_WDRC::CHA_DSL *dsl, BTNRH_WDRC::CHA_WDRC *gha, AudioEffectCompWDRC_F32 WDRCs[]) {
+  if (nchan > dsl->nchannel) {
+    myTympan.println(F("configureWDRC.configure: *** ERROR ***: nchan > dsl.nchannel"));
+    myTympan.print(F("    : nchan = ")); myTympan.println(nchan);
+    myTympan.print(F("    : dsl.nchannel = ")); myTympan.println(dsl->nchannel);
+  }
+
+  //now, loop over each channel
+  for (int i=0; i < nchan; i++) {
+
+    //logic and values are extracted from from CHAPRO repo agc_prepare.c
+    float atk = (float)dsl->attack;   //milliseconds!
+    float rel = (float)dsl->release;  //milliseconds!
+    float fs = (float) fs_Hz; // WEA override
+    float maxdB = (float) dsl->maxdB;
+    float exp_cr = (float) dsl->exp_cr[i];
+    float exp_end_knee = (float) dsl->exp_end_knee[i];
+    float tk = (float) dsl->tk[i];
+    float comp_ratio = (float) dsl->cr[i];
+    float tkgain = (float) dsl->tkgain[i];
+    float bolt = (float) dsl->bolt[i];
+
+    // adjust BOLT
+    float cltk = (float)gha->tk;
+    if (bolt > cltk) bolt = cltk;
+    if (tkgain < 0) bolt = bolt + tkgain;
+
+    //set the compressor's parameters
+    WDRCs[i].setSampleRate_Hz(fs);
+    WDRCs[i].setParams(atk,rel,maxdB,exp_cr,exp_end_knee,tkgain,comp_ratio,tk,bolt);
+
+  }
+}
+
 //define functions to setup the audio processing parameters
 #define N_FIR 96
 float firCoeff[N_CHAN][N_FIR];
@@ -134,6 +189,15 @@
   configureBroadbandWDRCs(audio_settings.sample_rate_Hz, &gha, &compBroadband);
   configurePerBandWDRCs(N_CHAN, audio_settings.sample_rate_Hz, &dsl, &gha, compPerBand);
 }
+
+
+//static void configureMultiBandWDRCasGHA(float fs_Hz, BTNRH_WDRC::CHA_DSL *dsl, BTNRH_WDRC::CHA_WDRC *gha,
+//    int nBB, AudioEffectCompWDRC_F32 *broadbandWDRCs,
+//    int nchan, AudioEffectCompWDRC_F32 *perBandWDRCs) {
+//
+//  configureBroadbandWDRCs(nBB, fs_Hz, gha, broadbandWDRCs);
+//  configurePerBandWDRCs(nchan, fs_Hz, dsl, gha, perBandWDRCs);
+//}

 // define the setup() function, the function that is called once when the device is booting
 void setup() {
@@ -241,68 +305,3 @@
       lastUpdate_millis = curTime_millis; //we will use this value the next time around.
     }
 };
-
-
-static void configureBroadbandWDRCs(float fs_Hz, BTNRH_WDRC::CHA_WDRC *gha, AudioEffectCompWDRC_F32 *WDRC) {
-  //logic and values are extracted from from CHAPRO repo agc_prepare.c...the part setting CHA_DVAR
-
-  //extract the parameters
-  float atk = (float)gha->attack;  //milliseconds!
-  float rel = (float)gha->release; //milliseconds!
-  //float fs = gha->fs;
-  float fs = (float)fs_Hz; // WEA override...not taken from gha
-  float maxdB = (float) gha->maxdB;
-  float exp_cr = (float)gha->exp_cr;
-  float exp_end_knee = (float)gha->exp_end_knee;
-  float tk = (float) gha->tk;
-  float comp_ratio = (float) gha->cr;
-  float tkgain = (float) gha->tkgain;
-  float bolt = (float) gha->bolt;
-
-  //set the compressor's parameters
-  WDRC->setSampleRate_Hz(fs);
-  WDRC->setParams(atk,rel,maxdB,exp_cr,exp_end_knee,tkgain,comp_ratio,tk,bolt);
-
-}
-
-static void configurePerBandWDRCs(int nchan, float fs_Hz, BTNRH_WDRC::CHA_DSL *dsl, BTNRH_WDRC::CHA_WDRC *gha, AudioEffectCompWDRC_F32 WDRCs[]) {
-  if (nchan > dsl->nchannel) {
-    myTympan.println(F("configureWDRC.configure: *** ERROR ***: nchan > dsl.nchannel"));
-    myTympan.print(F("    : nchan = ")); myTympan.println(nchan);
-    myTympan.print(F("    : dsl.nchannel = ")); myTympan.println(dsl->nchannel);
-  }
-
-  //now, loop over each channel
-  for (int i=0; i < nchan; i++) {
-
-    //logic and values are extracted from from CHAPRO repo agc_prepare.c
-    float atk = (float)dsl->attack;   //milliseconds!
-    float rel = (float)dsl->release;  //milliseconds!
-    float fs = (float) fs_Hz; // WEA override
-    float maxdB = (float) dsl->maxdB;
-    float exp_cr = (float) dsl->exp_cr[i];
-    float exp_end_knee = (float) dsl->exp_end_knee[i];
-    float tk = (float) dsl->tk[i];
-    float comp_ratio = (float) dsl->cr[i];
-    float tkgain = (float) dsl->tkgain[i];
-    float bolt = (float) dsl->bolt[i];
-
-    // adjust BOLT
-    float cltk = (float)gha->tk;
-    if (bolt > cltk) bolt = cltk;
-    if (tkgain < 0) bolt = bolt + tkgain;
-
-    //set the compressor's parameters
-    WDRCs[i].setSampleRate_Hz(fs);
-    WDRCs[i].setParams(atk,rel,maxdB,exp_cr,exp_end_knee,tkgain,comp_ratio,tk,bolt);
-
-  }
-}
-
-//static void configureMultiBandWDRCasGHA(float fs_Hz, BTNRH_WDRC::CHA_DSL *dsl, BTNRH_WDRC::CHA_WDRC *gha,
-//    int nBB, AudioEffectCompWDRC_F32 *broadbandWDRCs,
-//    int nchan, AudioEffectCompWDRC_F32 *perBandWDRCs) {
-//
-//  configureBroadbandWDRCs(nBB, fs_Hz, gha, broadbandWDRCs);
-//  configurePerBandWDRCs(nchan, fs_Hz, dsl, gha, perBandWDRCs);
-//}


debug

debug

--- _03-hx711-scale/_03-hx711-scale-v3-adaptor/_03-hx711-scale-esp-12/_03-hx711-scale-esp-12.ino
+++ _03-hx711-scale/_03-hx711-scale-v3-adaptor/_03-hx711-scale-esp-12/_03-hx711-scale-esp-12.ino
@@ -174,8 +174,8 @@
   inuse = digitalRead(nemoisOnPin);
   measured = requestHX711();

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

   if ( inuse == HIGH ) {
     digitalWrite(ledPin, HIGH);


added sensor type

added sensor type

--- aquaponicMCP/aquaponicMCP.ino
+++ aquaponicMCP/aquaponicMCP.ino
@@ -86,16 +86,19 @@
  * function or even in the data logger.
  */
 void SendData(){
-  String mystr = "['data', {'station': 'aquaponicStation', 'sensors': [{'sensor': 'aquaLight', 'value': ";
+  String mystr = "['data', {'station': 'aquaponicStation', 'sensors': [";
+  mystr += "{'sensor': 'aquaLight', 'type': 'lightsensor', 'value': ";
   mystr += analogRead(aquaLight) ;
-  mystr += "},{'sensor':'plantLight','value':";
+  mystr += "},{'sensor':'plantLight', 'type': 'lightsensor', 'value':";
   mystr += analogRead(plantLight);
-  mystr += "},{'sensor':'waterTurb','value':";
+  mystr += "},{'sensor':'waterTurb', 'type': 'cleanliness', 'value':";
   mystr += analogRead(waterTurbSensor);
-  mystr += "},{'sensor':'waterTemp','value':";
+  mystr += "},{'sensor':'waterTemp', 'type': 'temperature', 'value':";
   mystr += ReadTemp();
-  mystr += "},{'sensor':'OvenTemp','value':";
-  mystr += analogRead(ovenTemp);
+  mystr += "},{'sensor':'lightSwitch', 'type': 'lightswitch', 'value':";
+  mystr += powerIsOn;
+
+
   mystr += "}]}]";
   Serial.println(mystr);
 }


Exit Credits screen after credits scroll by

--- arduboy-game/arduboy-game.ino
+++ arduboy-game/arduboy-game.ino
@@ -259,10 +259,10 @@
 }

 void creditsScreen() {
-  scrollCredits(4, false);
-}
-
-void scrollCredits(byte y, bool quit) {
+  scrollCredits(4, NUM_CREDITS);
+}
+
+void scrollCredits(byte y, short line) {
   /**
      Recursive function for scrolling
      credits up screen
@@ -282,14 +282,11 @@
     printText(textBuf, 2, y + padding, (i == 0 ? 2 : 1));
     arduboy.display();
     padding = padding + 15;
-    if ( i + 1 == NUM_CREDITS && y + padding < 0) {
-      quit = true;
-    }
   }
   delay(1000);

-  if (!quit) {
-    scrollCredits(y - 15, quit);
+  if (line > 0) {
+    scrollCredits(y - 15, line - 1);
   }
 }


fix for initially firing bullets

fix for initially firing bullets

--- arduboy-game/arduboy-game.ino
+++ arduboy-game/arduboy-game.ino
@@ -432,11 +432,14 @@
         drawBoss(boss.x, boss.y, boss.type);
       }
     }
+
+    if(inGameAButtonLastPress > 80 || inGameBButtonLastPress > 60) {
+      for (byte i = 0; i < MAX_PLAYER_BULLETS; i++) {
+        playerBullets[i].draw();
+        playerBullets[i].update();
+      }
+    }

-    for (byte i = 0; i < MAX_PLAYER_BULLETS; i++) {
-      playerBullets[i].draw();
-      playerBullets[i].update();
-    }
     for (byte i = 0; i < MAX_ENEMIES; i++) {
       enemyBullets[i].draw();
       enemyBullets[i].update();
@@ -523,7 +526,7 @@
         inGameAButtonLastPress = inGameFrame;
         // Fire A weapon (single fire)
         for (byte i = 0; i < MAX_PLAYER_BULLETS; i++) {
-          if (!playerBullets[i].isVisible()) {
+          if (inGameAButtonLastPress > 80 && !playerBullets[i].isVisible()) {
             playerBullets[i].set(spaceShip.x, (spaceShip.y + 5), true, A_BULLET_DAMAGE);
             break;
           }
@@ -537,7 +540,7 @@
         inGameBButtonLastPress = inGameFrame;
         // Fire B weapon (rapid fire)
         for (byte i = 0; i < MAX_PLAYER_BULLETS; i++) {
-          if (!playerBullets[i].isVisible()) {
+          if (inGameBButtonLastPress > 80 && !playerBullets[i].isVisible()) {
             playerBullets[i].set(spaceShip.x, (spaceShip.y + 7), true, B_BULLET_DAMAGE);
             break;
           }


arduino switch improvements

arduino switch improvements

--- arduino/light_switch/light_switch.ino
+++ arduino/light_switch/light_switch.ino
@@ -1,46 +1,65 @@
+/* Web Switch Unit
+   This script is a part of my home automation setup
+   Vasily Klenov, 2014
+
+   If you are like me using ethernet shield based on ENC28J60
+   then you should replace '#include <Ethernet.h>' with '#include <UIPEthernet.h>'
+   inside RestClient.h (and all other libraries if you added any).
+   Otherwise if you are using more common ethernet shield
+   you should replace '#include <UIPEthernet.h>' with '#include <Ethernet.h>' in this file.
+   */
+
 #include <UIPEthernet.h> // https://github.com/ntruchsess/arduino_uip
 #include <RestClient.h>  //  https://github.com/csquared/arduino-restclient

-// можно попробовать переписать на получение стейта
-// типа по адресу /rest/items/Light_1/state

 #define DEBUG_SWITCHER 0
-#define OPENHAB_HOST "homer.local"
+#define OPENHAB_HOST "192.168.2.2"
 #define OPENHAB_PORT 8080
+
+#define SIZE(array) (sizeof(array) / sizeof(*array))
+
+// change this to your own unique value
+const byte mac[] = { 0x9C, 0x92, 0x27, 0x2D, 0xDA, 0x93 };

 const char* CONTENT_TYPE = "Content-Type:text/plain";
 const char* ACCEPT       = "Accept:application/json";

-const int main_led_pin  = 16;
-const int buttons_count = 3;
-// The Ethernet Controller (ENC28J60) uses the SPI pins (10, 11, 12, 13)
-const int buttons [buttons_count] = { 5, 3, 4 };
+const int status_led_pin  = 16;

-char* lights_url  = "/CMD?Light_X=TOGGLE";
-char* pin_as_char = "X";
-boolean button_was_pressed [buttons_count] = { 0, 0, 0 };
-unsigned long last_millis = 0;
+const int buttons []          = { 3, 4, 5 }; // The Ethernet Controller (ENC28J60) uses the SPI pins 10, 11, 12, 13
+boolean button_was_pressed [] = { 0, 0, 0 };

 unsigned long last_pressed_at = 0;
-unsigned long minimal_delay   = 1000;
+const unsigned long minimal_delay   = 1000;

 RestClient client = RestClient(OPENHAB_HOST, OPENHAB_PORT);

 void setup()
 {
-  pinMode(main_led_pin, OUTPUT);
+  pinMode(status_led_pin, OUTPUT);

   #ifdef DEBUG_SWITCHER
     Serial.begin(9600);
-    Serial.println("connect to network");
+    Serial.println("Buttons setup ...");
   #endif
-
- setup_buttons();
- sturtup_blink();
- byte mac[] = { 0x9C, 0x92, 0x27, 0x2D, 0xDA, 0x93 };
- if (client.begin(mac) == 0) {
+
+  setup_buttons();
+  sturtup_blink();
+
+  #ifdef DEBUG_SWITCHER
+    Serial.println("Connecting to network ...");
+  #endif
+
+  if (client.begin( const_cast<byte*>(mac) ) == 0 ) {
     #ifdef DEBUG_SWITCHER
       Serial.println("Failed to configure Ethernet using DHCP");
+    #endif
+  } else
+  {
+    #ifdef DEBUG_SWITCHER
+      Serial.println("OK!");
+      Serial.println(Ethernet.localIP());
     #endif
   }
 }
@@ -54,33 +73,32 @@
   delay(100);

   // send request to API if button pressed
-  for (int i=0; i<buttons_count; i++) {
+  for (int i=0; i<SIZE(buttons); i++) {
     if ( millis() - last_pressed_at > minimal_delay )
     {
       if(!button_was_pressed[i] && digitalRead(buttons[i]) == LOW) {
         #ifdef DEBUG_SWITCHER
           Serial.println("Button pressed!");
         #endif
-        digitalWrite( main_led_pin, HIGH );
+        control_led(HIGH);
         button_was_pressed[i] = true;

-        send_request_to_api( i+1 );
+        send_request_to_api( i );
         last_pressed_at = millis();
       }

       if(button_was_pressed[i] && digitalRead(buttons[i]) == HIGH)
       {
         button_was_pressed[i] = false;
-        digitalWrite( main_led_pin, LOW );
+        control_led(LOW);
       }
     }
   }
-
 }

 void setup_buttons()
 {
-  for (int i=0; i<buttons_count; i++) {
+  for (int i=0; i<SIZE(buttons); i++) {
     pinMode(buttons[i], INPUT);
     digitalWrite(buttons[i], HIGH); //internal pull-ups
   }
@@ -94,13 +112,14 @@

 int send_request_to_api(int b_number)
 {
-  lights_url[11] = lights_url_by_button_number(b_number);
   set_headers();
-  int status_code = client.get( lights_url );
+  int status_code;
+
+  status_code = client.get( lights_url_by_button_number(b_number) );

   #ifdef DEBUG_SWITCHER
-    Serial.println("GET query:");
-    Serial.print(lights_url);
+    Serial.print("GET query:");
+    Serial.println(lights_url_by_button_number(b_number));
     Serial.print("Status code from server: ");
     Serial.println(status_code);
   #endif
@@ -108,19 +127,38 @@
   return status_code;
 }

-char lights_url_by_button_number(int button_number)
+char* lights_url_by_button_number(int button_number)
 {
-  return (char)(((int)'0') + button_number);
+  switch (button_number) {
+    case 0:
+      return "/CMD?Smart_Switch_1=TOGGLE";
+    case 1:
+      return "/CMD?Smart_Switch_Day_Lights=TOGGLE";
+    case 2:
+      return "/CMD?Smart_Switch_Night_Lights=TOGGLE";
+    default:
+      return "";
+  }
 }

 void sturtup_blink()
 {
-  for (int i=0; i<30; i++) {
-    digitalWrite( main_led_pin, HIGH );
+  for (int i=0; i<5; i++) {
+    control_led(HIGH);
     delay(250);
-    digitalWrite( main_led_pin, LOW );
+    control_led(LOW);
     delay(250);
   }
 }

+void control_led(int state)
+{
+    #ifdef DEBUG_SWITCHER
+      if(state == LOW)
+        Serial.println("led is off");
+      else
+        Serial.println("led is on");
+    #endif
+    digitalWrite( status_led_pin, state );
+}


light_switch fix

light_switch fix

--- arduino/light_switch/light_switch.ino
+++ arduino/light_switch/light_switch.ino
@@ -1,10 +1,10 @@
 #include <UIPEthernet.h> // https://github.com/ntruchsess/arduino_uip
-#include <RestClient.h> //  https://github.com/csquared/arduino-restclient
+#include <RestClient.h>  //  https://github.com/csquared/arduino-restclient

 // можно попробовать переписать на получение стейта
 // типа по адресу /rest/items/Light_1/state

-#define DEBUG_SWITCHER
+#define DEBUG_SWITCHER 0
 #define OPENHAB_HOST "192.168.2.2"
 #define OPENHAB_PORT 8080

@@ -22,7 +22,7 @@
 unsigned long last_millis = 0;

 unsigned long last_pressed_at = 0;
-unsigned long minimal_delay   = 2000;
+unsigned long minimal_delay   = 1000;

 RestClient client = RestClient(OPENHAB_HOST, OPENHAB_PORT);

@@ -50,6 +50,8 @@
   #ifdef DEBUG_SWITCHER
     //Serial.println(".");
   #endif
+
+  delay(100);

   // send request to API if button pressed
   for (int i=0; i<buttons_count; i++) {
@@ -149,4 +151,4 @@
   }
 }

-
+


Update 2018-Firefighter.ino

Update 2018-Firefighter.ino

--- 2018-Firefighter/2018-Firefighter.ino
+++ 2018-Firefighter/2018-Firefighter.ino
@@ -6,6 +6,12 @@
 #define RIGHT_SERVO_PIN 5
 #define IR_PIN 6
 #define EXTINGUISHER_PIN 7
+#define MIC_PIN 43
+#define FLAME_LED 9
+#define MIC_LED 11
+#define BABY_LED 17
+#define CAMERA 15
+#define CAMERA_LED 16

 #define FRONT_US_ECHO   2
 #define FRONT_US_TRIG   3
@@ -69,7 +75,11 @@
       }
     }
   }
+  int detectSound(){return 0;}
+  int detectBaby(){return 0;}
+  int usingCamera(){return 0;)
 }
+

 void setup() {
   // put your setup code here, to run once:
@@ -78,6 +88,14 @@
   extinguisher.attach(EXTINGUISHER_PIN);

   pinMode(IR_PIN, INPUT);
+  pinMode(FLAME_LED, OUTPUT);
+
+  pinMode(MIC_PIN, INPUT);
+  pinMode(MIC_LED, OUTPUT);
+
+  pinMode(BABY_LED, OUTPT);
+
+  pinMode(CAMERA_LED, OUTPUT);
 }

 void loop() {
@@ -92,4 +110,27 @@
   extinguishFire();

   delay(100);
+
+  if (detectfire()){
+    digitalWrite(FLAME_LED, HIGH);
+  } else {
+    digitWrite(FLAME_LED, LOW);
+  }
+  if (usingCamera(){
+    digitalWrite(CAMERA_LED, HIGH);
+  } else {
+    digitalWrite(CAMERA_LED, LOW);
+  }
+  if(detectBaby(){
+    digitalWrite(BABY_LED, HIGH);
+  } else {
+    digitalWrite(BABY_LED, LOW);
+  }
+  if(detetSound){
+    digitalWrite(MIC_LED, HIGH);
+  } else {
+    digitalWrite(MIC_LED, LOW);
+  }
+ }
 }
+


Arduino is working from Arduino IDE. Sends status updates and light up the LED on input

--- arduino-usb-led/arduino-usb-led.ino
+++ arduino-usb-led/arduino-usb-led.ino
@@ -1,62 +1,69 @@
 const byte outputLedPin = 13; // Target LED to light up
 const byte inputLedPin = 12; // Lights when data is received
-const int updateDelay = 500; // Sends signals every x milliseconds
+const int updateDelay = 1000; // Sends signals every x milliseconds
 unsigned long currentMillis = 0; // Current millis count
 unsigned long lastUpdateMillis = 0; // Last time a message was sent (used for message loop)
 unsigned long startTime = 0; // Amount of milliseconds since the LED started shining
-unsigned int seconds = 0; // Amount of seconds the LED should shine
+unsigned long seconds = 0; // Amount of seconds the LED should shine

 void setup() {
+  delay(1000);
   Serial.begin(115200);
+  Serial.setTimeout(500);
   pinMode(outputLedPin, OUTPUT);
   pinMode(inputLedPin, OUTPUT);
+  currentMillis = millis();
+  startTime = currentMillis;
 }

 void loop() {
   currentMillis = millis();

+  // Check input
+  getSecondsFromInput(digitalRead(outputLedPin) == HIGH, inputLedPin, seconds);
+
   // Turn on/off LED
-  if(seconds > 0) {
-    startTime = turnLedOnOff(outputLedPin, seconds);
-  }
-
-  // Check input, but only if the amount of seconds have passed
-  if (seconds == 0) {
-    seconds = getSecondsFromInput(outputLedPin, inputLedPin);
-  }
+  turnLedOnOff(outputLedPin, seconds, startTime, currentMillis);

   // Send output message over serial
   if (currentMillis - lastUpdateMillis >= updateDelay) {
-    sendOutput(digitalRead(outputLedPin) == HIGH, currentMillis - startTime);
-    lastUpdateMillis = millis();
+    sendOutput(digitalRead(outputLedPin) == HIGH, currentMillis - startTime, seconds);
+    lastUpdateMillis = currentMillis;
   }
 }

-unsigned long turnLedOnOff(byte outputLedPin, unsigned int seconds) {
-  if (seconds > 0 && digitalRead(outputLedPin) == LOW) {
+void turnLedOnOff(byte outputLedPin, unsigned long &seconds, unsigned long &startTime, unsigned long currentMillis) {
+  if (seconds > 0 && currentMillis - startTime < seconds) {
+    if (digitalRead(outputLedPin) == LOW) {
+      startTime = millis();
+      Serial.println("start time set");
+    }
     digitalWrite(outputLedPin, HIGH);
-    return millis();
   } else {
     digitalWrite(outputLedPin, LOW);
-    return 0;
+    seconds = 0;
+    startTime = currentMillis;
   }
 }

-long getSecondsFromInput(byte outputLedPin, byte inputLedPin) {
+void getSecondsFromInput(boolean isOn, byte inputLedPin, unsigned long &seconds) {
   if (Serial.available() > 0) {
     digitalWrite(inputLedPin, HIGH);
-    return abs(Serial.parseInt()) * 1000;
+    seconds = Serial.parseInt() * 1000;
   } else {
     digitalWrite(inputLedPin, LOW);
   }
-  return 0;
 }

-void sendOutput(boolean on, unsigned long millis) {
-  String duration = "";
-  if(millis > 0) {
-    duration = ",\"duration\":" + millis;
+void sendOutput(boolean on, unsigned long ms, unsigned long seconds) {
+  String json = "{\"led\":{";
+  json += "\"status\":\"" + (String)(on ? "ON" : "OFF") + "\"";
+  if (on) {
+    json += ",\"duration\":" + (String)ms;
+    json += ",\"seconds\":" + (String)(seconds / 1000);
   }
-  Serial.println("{\"led\":{\"status:\"" + (String)(on ? "ON" : "OFF") + duration + "}}");
+  json += "}}";
+  Serial.println(json);
 }

+


Play on button state

Play on button state

--- buttmon/buttmon.ino
+++ buttmon/buttmon.ino
@@ -13,6 +13,8 @@
 };

 const int SPEAKER_PIN = 6;
+const int BUTTON_PIN = 2;
+
 const char server_host[] = "ournewballandchain.com";
 unsigned int server_port = 8008;
 char log_message[] = "BWAANG";
@@ -60,9 +62,12 @@
 }

 void loop() {
-  play_song();
-  send_message();
-  delay(1000);
+  int buttonState = digitalRead(BUTTON_PIN);
+  if (buttonState == HIGH) {
+    play_song();
+    send_message();
+  }
+
 }

 void setup() {


add cases, cleanup

add cases, cleanup

--- main/main.ino
+++ main/main.ino
@@ -140,10 +140,6 @@

 void loop() {

-  //message->id = 0x5ea; //group 1514 //0x5e8;
-  //message->header.rtr = 0;
-  //message->header.length = 8;
-
   currentMillis = millis();
   if(currentMillis - lastMillis >= interval) {
     lastMillis = currentMillis;
@@ -155,9 +151,6 @@
     lcd.print(engine_afr.currentValue);
     draw_bar(engine_afr.currentValue, 1, 10.0, 20.0);

-    //Serial.println(tgt);
-    //Serial.println((double)badDataCount / (double)goodDataCount);
-
   }

   unsigned char len = 0;
@@ -171,48 +164,27 @@
         unsigned int canId = CAN.getCanId();

         switch(canId) {
+          case 1512:
+
+            break;
+          case 1513:
+
+            break;
           case 1514:
             engine_tgt.currentValue = (double)buf[0] / 10.0;
             engine_afr.currentValue = (double)buf[1] / 10.0;
             break;
+          case 1515:
+
+            break;
+          case 1516:
+
+            break;
           default:
             //do nothing
             break;
         }
-          /*
-        if(canId == 1514) {
-          Serial.println("-----------------------------");
-          Serial.print("Get data from ID: ");
-          Serial.println(canId, HEX);
-          tgt = (double)buf[0] / 10.0;
-          afr = (double)buf[1] / 10.0;
-          for(int i = 0; i<2; i++)    // print the data
-          {
-              Serial.print(buf[i]);
-              Serial.print("\t");
-          }
-          Serial.println();
-        }
-        */
-
-
-  }
-
-
-  if(messageReceived == 1) {
-    if(currentMillis - lastMillis >= interval) {
-      lastMillis = currentMillis;
-      lcd.setCursor(4, 2);
-      lcd.print(tgt);
-      //Serial.println(tgt);
-      Serial.println((double)badDataCount / (double)goodDataCount);
-
-    }
-    messageReceived = 0;
-  }
-
-
-
+  }

 }


start playing with can bus

start playing with can bus

--- main/main.ino
+++ main/main.ino
@@ -3,7 +3,6 @@
 #include <global.h>
 #include <mcp2515.h>
 #include <mcp2515_defs.h>
-
 #include <LiquidCrystal.h>
 #include <math.h>

@@ -66,6 +65,10 @@
   B11111,
   B11111
 };
+
+
+char can_buffer[64];
+char can_data;

 //possible parameters to display
 double  engine_afr;         //AFR
@@ -79,7 +82,10 @@
 int     engine_clt;         //coolant temp
 int     engine_iat;         //intake air temp

+
+
 void setup() {
+

   lcd.createChar(0, fill1);
   lcd.createChar(1, fill2);
@@ -97,9 +103,36 @@
   pinMode(BLUELITE, OUTPUT);

   setBacklight(255, 0, 0);
+
+  Serial.begin(9600);
+
+  //Initialize CAN Controller
+  if(Canbus.init(CANSPEED_500))  /* Initialize MCP2515 CAN controller at the specified speed */
+  {
+    Serial.println("CAN Init Ok!");
+    //delay(1500);
+  }
+  else {
+    Serial.println("Can't init CAN");
+  }
+
+
 }

 void loop() {
+
+  ecu_req(can_buffer);
+  //Serial.print("buffer: ");
+  //Serial.println(can_buffer);
+  //Canbus.ecu_req(ENGINE_RPM,buffer);
+  //Canbus.message_rx(buffer);
+
+  //engine_rpm = buffer;
+  //Serial.print("Engine RPM: "); //Uncomment for Serial debugging
+  //Serial.println("buffer: " + buffer);
+  delay(1500);
+
+
   double afr = 12.5;
   double tgt = 14.7;

@@ -142,3 +175,77 @@
   analogWrite(BLUELITE, b);
 }

+char ecu_req(char *buffer)
+{
+  tCAN message;
+  float engine_data;
+  int timeout = 0;
+  char message_ok = 0;
+  // Prepair message
+  message.id = PID_REQUEST;
+  message.header.rtr = 0;
+  message.header.length = 8;
+  message.data[0] = 0x02;
+  message.data[1] = 0x01;
+  message.data[2] = "all";
+  message.data[3] = 0x00;
+  message.data[4] = 0x00;
+  message.data[5] = 0x00;
+  message.data[6] = 0x00;
+  message.data[7] = 0x00;
+
+
+  mcp2515_bit_modify(CANCTRL, (1<<REQOP2)|(1<<REQOP1)|(1<<REQOP0), 0);
+
+  if (mcp2515_send_message(&message)) {
+    Serial.println("message sent");
+  }
+  else {
+    Serial.println("message not sent");
+  }
+        if (mcp2515_check_message())
+        {
+          Serial.println("after check message");
+          if (mcp2515_get_message(&message))
+          {
+                  engine_data =  ((message.data[3]*256) + message.data[4])/4;
+                  sprintf(buffer,"%d rpm ",(int) engine_data);
+                  Serial.print("buffer 1: ");
+                  Serial.println(buffer);
+
+                  engine_data =  message.data[3] - 40;
+                  sprintf(buffer,"%d degC",(int) engine_data);
+                  Serial.print("buffer 1: ");
+                  Serial.println(buffer);
+
+                  engine_data =  message.data[3];
+                  sprintf(buffer,"%d km ",(int) engine_data);
+                  Serial.print("buffer 1: ");
+                  Serial.println(buffer);
+
+                  engine_data =  ((message.data[3]*256) + message.data[4])/100;
+                  sprintf(buffer,"%d g/s",(int) engine_data);
+                  Serial.print("buffer 1: ");
+                  Serial.println(buffer);
+
+                  engine_data = message.data[3]*0.005;
+                  sprintf(buffer,"%d V",(int) engine_data);
+                  Serial.print("buffer 1: ");
+                  Serial.println(buffer);
+
+                  engine_data = (message.data[3]*100)/255;
+                  sprintf(buffer,"%d %% ",(int) engine_data);
+                  Serial.print("buffer 1: ");
+                  Serial.println(buffer);
+
+            return buffer;
+          }
+          else {
+            Serial.println("nothing to get");
+          }
+        }
+        else {
+          Serial.println("check/else");
+        }
+
+}


Just changed a comment

Just changed a comment


Improve interrupt setup comments

Improve interrupt setup comments

--- Arduino/LightPlayer/LightPlayer.ino
+++ Arduino/LightPlayer/LightPlayer.ino
@@ -208,9 +208,9 @@
   nextFile();
   startMillis = millis();

-  PCMSK1 = B1111; // Enable interrupts for inputs A0, A1, A2, A3
-  PCIFR  |= bit(PCIF1);   // clear any outstanding interrupts
-  PCICR  |= bit(PCIE1);   // enable pin change interrupts for D8 to D13
+  PCIFR |= bit(PCIF1); // clear any pending port C (A0-A5) interrupts
+  PCMSK1 = B1111; // monitor pins A0 through A3 for changes, but not A4 or A5
+  PCICR |= bit(PCIE1); // begin interrupting for pin changes on port C (A0-A5)
 }

 void printPendingOperations(PendingOperations & ops)


snedcheck when mode changed

snedcheck when mode changed

--- _04-lcd-dust/a-01-esp01-i2c/a-01-esp01-i2c.ino
+++ _04-lcd-dust/a-01-esp01-i2c/a-01-esp01-i2c.ino
@@ -254,66 +254,42 @@
   client.loop();
 }

-void ICACHE_RAM_ATTR callback(char* intopic, byte* inpayload, unsigned int length)
-{
-  String receivedtopic = intopic;
-  String receivedpayload ;
-
-  if ( receivedtopic == "esp8266/arduino/s03" || receivedtopic == "clients/dust" )
-  {
-    return;
-  }
-
-  for (int i = 0; i < length; i++)
-  {
-    receivedpayload += (char)inpayload[i];
-  }
-
-  if (DEBUG_PRINT)
-  {
-    syslogPayload = "mqtt ====> ";
-    syslogPayload += intopic;
-    syslogPayload += " ====> ";
-    syslogPayload += receivedpayload;
-    //sendUdpSyslog(syslogPayload);
-  }
-
-  if ( receivedpayload == "{\"CHECKING\":\"1\"}")
-  {
+void sendCheck()
+{
     String check_payload = "ac status: ";
     if (bac_timer_mode)
     {
       if (data_curr.ac_mode == 0)
       {
-        check_payload += "timer:off";
+        check_payload += ":timer_clock::black_square_for_stop:";
       }
       else
       {
-        check_payload += "timer:on";
+        check_payload += ":timer_clock::arrows_counterclockwise:";
       }
     }
     else
     {
       if (data_curr.ac_mode == 0)
       {
-        check_payload += "off";
+        check_payload += ":black_square_for_stop:";
       }
       else
       {
-        check_payload += "on";
+        check_payload += ":arrows_counterclockwise:";
       }
     }
     check_payload += "\r\n";
-    check_payload += "ac temp set : ";
+    check_payload += "ac :thermometer: set : ";
     check_payload += data_curr.ac_temp;
     check_payload += "\r\n";
     check_payload += "ac flow set : ";
     check_payload += data_curr.ac_flow;
     check_payload += "\r\n";
-    check_payload += "temp inside: ";
+    check_payload += ":thermometer: inside: ";
     check_payload += ((data_mqtt.tempinside1 + data_mqtt.tempinside2) / 2);
     check_payload += "\r\n";
-    check_payload += "temp outside: ";
+    check_payload += ":thermometer: outside: ";
     check_payload += data_mqtt.tempoutside;
     check_payload += "\r\n";
     check_payload += "humidity: ";
@@ -330,7 +306,36 @@
     check_payload += "/";
     check_payload += data_mqtt.hosttwo;

-    sendmqttMsg(reporttopic, check_payload);
+    sendmqttMsg(reporttopic, check_payload);
+}
+
+void ICACHE_RAM_ATTR callback(char* intopic, byte* inpayload, unsigned int length)
+{
+  String receivedtopic = intopic;
+  String receivedpayload ;
+
+  if ( receivedtopic == "esp8266/arduino/s03" || receivedtopic == "clients/dust" )
+  {
+    return;
+  }
+
+  for (int i = 0; i < length; i++)
+  {
+    receivedpayload += (char)inpayload[i];
+  }
+
+  if (DEBUG_PRINT)
+  {
+    syslogPayload = "mqtt ====> ";
+    syslogPayload += intopic;
+    syslogPayload += " ====> ";
+    syslogPayload += receivedpayload;
+    //sendUdpSyslog(syslogPayload);
+  }
+
+  if ( receivedpayload == "{\"CHECKING\":\"1\"}")
+  {
+    sendCheck();
     return;
   }

@@ -951,6 +956,7 @@
         Wire.beginTransmission(SLAVE_ADDRESS);
         I2C_writeAnything(data_esp);
         Wire.endTransmission();
+        sendCheck();
         bhaveData = false;
       }


That bit where payload is an array of bytes which are each the character you seek.. onwards to decoding that then ;

--- firmware/examples/readTag/readtag.ino
+++ firmware/examples/readTag/readtag.ino
@@ -22,9 +22,10 @@
                 for (i = 0; i < tagMessage.getRecordCount()   ; i++)  {
                          //
                          NdefRecord tagRecord = tagMessage.getRecord(i);
+                         tagRecord.print();
                          int payloadLength = tagRecord.getPayloadLength();
-                         char *tagMessage[payloadLength];
-                         tagRecord.print();
+                         byte payload[payloadLength];
+                         tagRecord.getPayload(payload);

                 }
         }


v3.7 Opps

v3.7 Opps

--- WeatherDisplay.ino
+++ WeatherDisplay.ino
@@ -456,6 +456,7 @@
     time += (TimeErrorOffset + 2);
   }
   else if (time == 0) {
+    time += TimeErrorOffset;
     convertDate(time, &year, &month, &day);
   }
   else {


add monitor example

add monitor example

--- dynamixel_workbench_toolbox/DynamixelWorkbench/example/o_Monitor/o_Monitor.ino
+++ dynamixel_workbench_toolbox/DynamixelWorkbench/example/o_Monitor/o_Monitor.ino
@@ -23,29 +23,137 @@
 #define DXL_BUS_SERIAL3 "3"            //Dynamixel on Serial3(USART3)  <-OpenCM 485EXP
 #define DXL_BUS_SERIAL4 "/dev/ttyUSB0" //Dynamixel on Serial3(USART3)  <-OpenCR

-#define BAUDRATE  57600
-#define DXL_ID    1
+String cmd[5];

 DynamixelWorkbench dxl_wb;
+uint8_t get_id[16];
+uint8_t dxl_cnt = 0;

 void setup()
 {
   Serial.begin(57600);
   while(!Serial);

-  dxl_wb.begin(DXL_BUS_SERIAL3, BAUDRATE);
-  dxl_wb.ping(DXL_ID);
-
-  dxl_wb.jointMode(DXL_ID);
+  Serial.println("---------------------------------");
+  Serial.println("Set portHandler First");
+  Serial.println("---------------------------------");
+  Serial.println("port (BAUD)");
+  Serial.println("scan");
+  Serial.println("ping   (ID)");
+  Serial.println("id     (ID) (NEW_ID)");
+  Serial.println("baud   (ID) (NEW_BAUD)");
+  Serial.println("joint  (ID) (GOAL_POSITION)");
+  Serial.println("wheel  (ID) (GOAL_VELOCITY)");
+  Serial.println("reboot (ID) ");
+  Serial.println("reset  (ID) ");
+  Serial.println("---------------------------------");
 }

 void loop()
 {
-  dxl_wb.goalPosition(DXL_ID, 0);
+  if (Serial.available())
+  {
+    String read_string = Serial.readStringUntil('\n');
+
+    read_string.trim();
+
+    split(read_string, ' ', cmd);
+
+    if (cmd[0] == "port")
+    {
+      uint32_t baud = cmd[1].toInt();
+      dxl_wb.begin(DXL_BUS_SERIAL3, baud);
+    }
+    else if (cmd[0] == "scan")
+    {
+      dxl_cnt = dxl_wb.scan(get_id);
+    }
+    else if (cmd[0] == "ping")
+    {
+      uint8_t id = cmd[1].toInt();
+
+      dxl_wb.ping(id);
+    }
+    else if (cmd[0] == "id")
+    {
+      uint8_t id     = cmd[1].toInt();
+      uint8_t new_id = cmd[2].toInt();
+
+      if (dxl_wb.setID(id, new_id))
+        Serial.println("Succeed to change ID");
+      else
+        Serial.println("Failed");
+
+    }
+    else if (cmd[0] == "baud")
+    {
+      uint8_t  id       = cmd[1].toInt();
+      uint32_t new_baud = cmd[2].toInt();
+
+      if (dxl_wb.setBaud(id, new_baud))
+        Serial.println("Succeed to change BaudRate");
+      else
+        Serial.println("Failed");
+    }
+    else if (cmd[0] == "joint")
+    {
+      uint8_t id    = cmd[1].toInt();
+      uint16_t goal = cmd[2].toInt();
+
+      dxl_wb.jointMode(id);
+      if (dxl_wb.goalPosition(id, goal))
+       Serial.println("Succeed!!");
+      else
+        Serial.println("Failed");
+    }
+    else if (cmd[0] == "wheel")
+    {
+      uint8_t id    = cmd[1].toInt();
+      int32_t goal = cmd[2].toInt();
+
+      dxl_wb.wheelMode(id);
+      if (dxl_wb.goalSpeed(id, goal))
+        Serial.println("Succeed!!");
+      else
+        Serial.println("Failed");
+    }
+    else if (cmd[0] == "reboot")
+    {
+      uint8_t id = cmd[1].toInt();
+
+      dxl_wb.reboot(id);
+    }
+    else if (cmd[0] == "reset")
+    {
+      uint8_t id = cmd[1].toInt();
+
+      dxl_wb.reset(id);
+    }
+  }
+}
+
+void split(String data, char separator, String* temp)
+{
+	int cnt = 0;
+	int get_index = 0;
+
+  String copy = data;

-  delay(2000);
+	while(true)
+	{
+		get_index = copy.indexOf(separator);

-  dxl_wb.goalPosition(DXL_ID, 2000);
+		if(-1 != get_index)
+		{
+			temp[cnt] = copy.substring(0, get_index);

-  delay(2000);
+			copy = copy.substring(get_index + 1);
+		}
+		else
+		{
+      temp[cnt] = copy.substring(0, copy.length());
+			break;
+		}
+		++cnt;
+	}
 }


array of memory buttons

array of memory buttons

--- vfobox.ino
+++ vfobox.ino
@@ -43,8 +43,8 @@
 #define RESET 7

 // set up memory push buttons
-#define M1Sw 8
-#define M2Sw 9
+#define MEM_BUTTON_START_PIN  8  // digital pin where mem buttons start
+#define NUMBER_MEM_BUTTONS    2  // how many mem buttons

 const double bandStart = 100000;  // start of Gnerator at 100 KHZ
 const double bandEnd = 40000000; // End of Generator at 40 MHz --signal will be a bit flaky!
@@ -58,10 +58,8 @@
 long lastBlink = 0;
 boolean blinkState = false;

-boolean m1armed = false;
-boolean m2armed = false;
-long lastM1 = 0;
-long lastM2 = 0;
+boolean mem_armed[NUMBER_MEM_BUTTONS];
+long last_mem[NUMBER_MEM_BUTTONS];

 int eeAddressStart = 0;

@@ -87,10 +85,12 @@
   pinMode(RotEncSwPin, INPUT_PULLUP);

   // Set up memory buttons
-  pinMode(M1Sw, INPUT_PULLUP);
-  pinMode(M2Sw, INPUT_PULLUP);
-
-
+  for (int buttons=0; buttons < NUMBER_MEM_BUTTONS; buttons++) {
+    mem_armed[buttons] = false;
+    last_mem[buttons] = 0;
+    pinMode(MEM_BUTTON_START_PIN + buttons,INPUT_PULLUP);
+  }
+
  // start on M1 freq
   EEPROM.get(eeAddressStart,freq);
   if(freq < bandStart || freq > bandEnd) {
@@ -157,52 +157,34 @@
   }

   // handle memory buttons
-  if(!m1armed && !digitalRead(M1Sw) && millis() - lastM1 > 50) {
-    lastM1 = millis();
-    m1armed = true;
-  }
-  if(m1armed && digitalRead(M1Sw) && millis() - lastM1 > 50) {
-    //pushed, but for how long?
-    lcd.setCursor(0,1);
-    if(millis() - lastM1 > 500) {
-    // long push = commit to memory
-    EEPROM.put(eeAddressStart,freq);
-    lcd.print("m1 stored");
-    } else {
-    // short push = qsy to memory frequency
-    EEPROM.get(eeAddressStart,freq);
-    lcd.print("recall m1");
-    send_frequency(freq);
-    display_frequency(freq);
-    }
-    m1armed = false;
-    lastM1 = millis();
-  }
-
-//yes, duplicative code, could make an array of it...
-//maybe optimize later
-
-  if(!m2armed && !digitalRead(M2Sw) && millis() - lastM2 > 50) {
-    lastM2 = millis();
-    m2armed = true;
-  }
-  if(m2armed && digitalRead(M2Sw) && millis() - lastM2 > 50) {
-    //pushed, but for how long?
-    lcd.setCursor(0,1);
-    if(millis() - lastM2 > 500) {
-    // long push = commit to memory
-    EEPROM.put(eeAddressStart+sizeof(double),freq);
-    lcd.print("m2 stored");
-    } else {
-    // short push = qsy to memory frequency
-    EEPROM.get(eeAddressStart+sizeof(double),freq);
-    lcd.print("recall m2");
-    send_frequency(freq);
-    display_frequency(freq);
-    }
-    m2armed = false;
-    lastM2 = millis();
-  }
+  for (int buttons = 0; buttons < NUMBER_MEM_BUTTONS; buttons++) {
+    if(!mem_armed[buttons] && !digitalRead(MEM_BUTTON_START_PIN+buttons) && millis() - last_mem[buttons] > 50) {
+      last_mem[buttons] = millis();
+      mem_armed[buttons] = true;
+    }
+    if(mem_armed[buttons] && digitalRead(MEM_BUTTON_START_PIN+buttons) && millis() - last_mem[buttons] > 50) {
+      //pushed, but for how long?
+      lcd.setCursor(0,1);
+      if(millis() - last_mem[buttons] > 500) {
+      // long push = commit to memory
+      EEPROM.put(eeAddressStart+buttons*sizeof(double),freq);
+      lcd.print("m");
+      lcd.print(buttons);
+      lcd.print(" stored");
+      } else {
+      // short push = qsy to memory frequency
+      EEPROM.get(eeAddressStart+buttons*sizeof(double),freq);
+      lcd.print("recall m");
+      lcd.print(buttons);
+      send_frequency(freq);
+      display_frequency(freq);
+      }
+      mem_armed[buttons] = false;
+      last_mem[buttons] = millis();
+    }
+  }
+
+
 }

 // subroutine to display the frequency...


Removed a bunch of senseless comments. Move call of begin on the 9dof sensor into the setupSensor method, since its part of the sensor setup... Removed a couple of unused methods that I didn't really plan on using in the future.

--- InfinityGoggles.ino
+++ InfinityGoggles.ino
@@ -1,10 +1,3 @@
-// Googly Eye Goggles
-// By Bill Earl
-// For Adafruit Industries
-// Edited by
-// Charlie Hendricks
-// because I want what I want?
-//
 // The googly eye effect is based on a physical model of a pendulum.
 // The pendulum motion is driven by accelerations in 2 axis.
 // Eye color varies with orientation of the magnetometer
@@ -15,13 +8,11 @@
 #include <Adafruit_Simple_AHRS.h>
 #include <FastLED.h>

-//FASTLED_USING_NAMESPACE;
-
 #define DATAPIN_LEFT    0
 #define CLOCKPIN_LEFT   1
 #define DATAPIN_RIGHT    6
 #define CLOCKPIN_RIGHT   9
-#define NUM_LEDS 21 //Number of LEDS per lense
+#define NUM_LEDS 21

 #define FRAMES_PER_SECOND  5
 #define BRIGHTNESS         120
@@ -49,13 +40,11 @@
 const float pupilRadius = 2; // half-width of pupil (in pixels)

 long gestureStart = 0;
-long gestureHoldTime = 1500;
+long gestureHoldTime = 1700;

 uint8_t hue = 0;
-uint8_t currentPatternNumber = 0; // Index number of which pattern is current
-
-
-// List of patterns to cycle through.  Each is defined as a separate function below.
+uint8_t currentPatternNumber = 1;
+
 typedef void (*SimplePattern)();

 typedef void (*Action)();
@@ -82,32 +71,24 @@
     FastLED.addLeds<APA102, DATAPIN_RIGHT, CLOCKPIN_RIGHT>(rightLense, NUM_LEDS).setCorrection(TypicalLEDStrip);
     FastLED.setBrightness(BRIGHTNESS);

-    // Try to initialise the 9DOF
+    setupSensor();
+    patterns[currentPatternNumber].pattern();
+}
+
+void setupSensor() {
     if (!lsm.begin()) {
         while (1);
     }
-
-    // Intitialize the sensors and start with default pattern
-    setupSensor();
-    patterns[currentPatternNumber].pattern();
-}
-
-void setupSensor() {
-    // 1.) Set the accelerometer range
     lsm.setupAccel(lsm.LSM9DS0_ACCELRANGE_2G); // 2G, 4G, 6G, 8G, 16G
-    // 2.) Set the magnetometer sensitivity
     lsm.setupMag(lsm.LSM9DS0_MAGGAIN_2GAUSS); //2GAUSS,4GAUSS,8GAUSS,12GAUSS
-    // 3.) Setup the gyroscope. Options are: 245DPS,500DPS,2000DPS
-    lsm.setupGyro(lsm.LSM9DS0_GYROSCALE_245DPS);
+    lsm.setupGyro(lsm.LSM9DS0_GYROSCALE_245DPS); //245DPS,500DPS,2000DPS
 }

 void loop(void) {
-    // Read the magnetometer and determine the compass heading:
     lsm.getEvent(&accel, &mag, &gyro, &temp);
-    // Check for mode change commands
+
     checkForGestures(accel);

-    // Call the current pattern function once, updating the 'leds' array
     patterns[currentPatternNumber].action();
 }

@@ -145,12 +126,12 @@
 void checkForGestures(sensors_event_t accel) {
     if (accel.acceleration.x < gestureThreshold) {
         if (millis() - gestureStart > gestureHoldTime) {
-            gestureStart = millis(); // reset timer
+            gestureStart = millis();
             activateGestureModeSelect();
         }
     }
     else {
-        gestureStart = millis(); // reset timer
+        gestureStart = millis();
     }
 }

@@ -198,7 +179,6 @@
  * some way. All can be used as an 'action' type
  *******************************************************************/
 //TODO: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 rotateClockwise() {
     shift(leftLense, NUM_LEDS, false);
     shift(rightLense, NUM_LEDS, false);
@@ -257,36 +237,38 @@
         leftLense[i] = ColorFromPalette(palette, hue + (i * 2), beat - hue + (i * 8));
     }
     FastLED.show();
-    EVERY_N_MILLISECONDS( 20 ) { hue++; } // slowly cycle the "base color" through the rainbow
-}
-
-void sinelon()
-{
-    // a colored dot sweeping back and forth, with fading trails
-    fadeToBlackBy( rightLense, NUM_LEDS, 20);
-    fadeToBlackBy( leftLense, NUM_LEDS, 20);
-    int pos = beatsin16(13,0,NUM_LEDS);
-    rightLense[pos] += CHSV( hue, 200, 192);
-    leftLense[pos] += CHSV( hue, 200, 192);
-
-    FastLED.show();
-    EVERY_N_MILLISECONDS( 20 ) { hue++; } // slowly cycle the "base color" through the rainbow
+    EVERY_N_MILLISECONDS(20)
+    { hue++; } // slowly cycle the "base color" through the rainbow
+}
+
+// a colored dot sweeping back and forth, with fading trails
+void sinelon() {
+    fadeToBlackBy(rightLense, NUM_LEDS, 20);
+    fadeToBlackBy(leftLense, NUM_LEDS, 20);
+    int pos = beatsin16(13, 0, NUM_LEDS);
+    rightLense[pos] += CHSV(hue, 200, 192);
+    leftLense[pos] += CHSV(hue, 200, 192);
+
+    FastLED.show();
+    EVERY_N_MILLISECONDS(20)
+    { hue++; } // slowly cycle the "base color" through the rainbow
 }

 void juggle() {
     // eight colored dots, weaving in and out of sync with each other
-    fadeToBlackBy( rightLense, NUM_LEDS, 20);
-    fadeToBlackBy( leftLense, NUM_LEDS, 20);
+    fadeToBlackBy(rightLense, NUM_LEDS, 20);
+    fadeToBlackBy(leftLense, NUM_LEDS, 20);
     byte dothue = 0;
-    for( int i = 0; i < 8; i++) {
-        rightLense[beatsin16(i+7,0,NUM_LEDS)] |= CHSV(dothue, 200, 180);
-        leftLense[beatsin16(i+7,0,NUM_LEDS)] |= CHSV(dothue, 200, 180);
+    for (int i = 0; i < 8; i++) {
+        rightLense[beatsin16(i + 7, 0, NUM_LEDS)] |= CHSV(dothue, 200, 180);
+        leftLense[beatsin16(i + 7, 0, NUM_LEDS)] |= CHSV(dothue, 200, 180);
         dothue += 32;
     }

     FastLED.show();
-    EVERY_N_MILLISECONDS( 20 ) { hue++; } // slowly cycle the "base color" through the rainbow
+    EVERY_N_MILLISECONDS(20)
+    { hue++; } // slowly cycle the "base color" through the rainbow
 }

 void pendulum() {
@@ -346,7 +328,7 @@
     }
     for (int i = 0; i < NUM_LEDS; i++) {
         int rightIndex = i;
-        int leftIndex = wrapAround(i - 10); // This is because the strips aren't installed in the same place
+        int leftIndex = wrapAround(i - 10); // This is because the strips aren't installed in the same orientation :/
         boolean turnedOn = false;
         for (int j = 0; j < (pupilRadius * 2 + 1); j++) {
             if (lightOn[j] == i) {
@@ -465,27 +447,6 @@
  * These animations that hold up the loop, so you wont be able to
  * check for gestures, or anything of the such.
  *******************************************************************/
-
-// gradual spin up
-void spinUp() {
-    for (int i = 300; i > 0; i -= 20) {
-        spin(CRGB::White, 1, i);
-    }
-    pos = 0;
-    // leave it with some momentum and let it 'coast' to a stop
-    MomentumH = 3;
-}
-
-// Gradual spin down
-void spinDown() {
-    for (int i = 1; i < 300; i += 20) {
-        spin(CRGB::White, 1, i);
-    }
-    // Stop it dead at the top and let it swing to the bottom on its own
-    pos = 0;
-    MomentumH = MomentumV = 0;
-}
-
 // utility function for feedback on mode changes.
 void spin(CRGB color, int count, int time) {
     for (int j = 0; j < count; j++) {


Use a NTC sensor also for indoor temperature measurement

--- tempserver.ino
+++ tempserver.ino
@@ -2,9 +2,7 @@
 #include <Ethernet.h>

 // Input pins
-const int insideTempPin = A0;
 const int photoresistorPin = A1;
-const int thermistorPin = A2;

 // Enter a MAC address and IP address for your controller below.
 // The IP address will be dependent on your local network:
@@ -22,19 +20,8 @@
    */
 const int SAMPLE_NUMBER = 10;

-/* In order to use the Beta equation, we must know our other resistor
-   within our resistor divider. If you are using something with large tolerance,
-   like at 5% or even 1%, measure it and place your result here in ohms. */
-const double BALANCE_RESISTOR = 9800.0;
-
 // This helps calculate the thermistor's resistance (check article for details).
 const double MAX_ADC = 1023.0;
-
-/* This is thermistor dependent and it should be in the datasheet, or refer to the
-   article for how to calculate it using the Beta equation.
-   I had to do this, but I would try to get a thermistor with a known
-   beta if you want to avoid empirical calculations. */
-const double BETA = 3379.1;

 /* This is also needed for the conversion equation as "typical" room temperature
    is needed as an input. */
@@ -72,11 +59,11 @@
           client.println("Connection: close");
           client.println();
           client.print("{\"inside_temp\":");
-          client.print(readTemperature());
+          client.print(readThermistor(A3, 9750.0, 3950.0));
           client.print(", \"inside_light\":");
           client.print(analogRead(photoresistorPin));
           client.print(", \"outside_temp\":");
-          client.print(readThermistor());
+          client.print(readThermistor(A2, 9800.0, 3380.0));
           client.println("}");
           break;
         }
@@ -97,15 +84,6 @@
   }
 }

-/**
- * Reads the voltage from TMP36 sensor.
- * Returns the temperature in degrees Celsius.
- */
-float readTemperature() {
-  float voltage = (analogRead(insideTempPin) / 1024.0) * 5.0;
-  return (voltage - 0.5) * 100;
-}
-
 // The code below is from https://www.allaboutcircuits.com/projects/measuring-temperature-with-an-ntc-thermistor/
 /**
 This function reads the analog pin as shown below. Converts voltage signal
@@ -124,7 +102,7 @@
                                     |
                                Analog Pin
 */
-double readThermistor() {
+double readThermistor(int thermistorPin, double balanceResistor, double beta) {
   // variables that live in this function
   double rThermistor = 0;            // Holds thermistor resistance value
   double tKelvin     = 0;            // Holds calculated temperature
@@ -151,7 +129,7 @@

   /* Here we calculate the thermistor’s resistance using the equation
      discussed in the article. */
-  rThermistor = BALANCE_RESISTOR * ( (MAX_ADC / adcAverage) - 1);
+  rThermistor = balanceResistor * ( (MAX_ADC / adcAverage) - 1);

   /* Here is where the Beta equation is used, but it is different
      from what the article describes. Don't worry! It has been rearranged
@@ -160,8 +138,8 @@
      better at algebra. And if not, just use what is shown here and take it
      for granted or input the formula directly from the article, exactly
      as it is shown. Either way will work! */
-  tKelvin = (BETA * ROOM_TEMP) /
-            (BETA + (ROOM_TEMP * log(rThermistor / RESISTOR_ROOM_TEMP)));
+  tKelvin = (beta * ROOM_TEMP) /
+            (beta + (ROOM_TEMP * log(rThermistor / RESISTOR_ROOM_TEMP)));

   /* I will use the units of Celsius to indicate temperature. I did this
      just so I can see the typical room temperature, which is 25 degrees


Update h_SDI-12_slave_implementation.ino

To avoid the chance that the slave has to enter in handle interrupt pin vector, we set de Hold mode. Doing that we reinforce that sensor will do all the code they have to do and continue to listen just after forceListen() function set it again.

--- examples/h_SDI-12_slave_implementation/h_SDI-12_slave_implementation.ino
+++ examples/h_SDI-12_slave_implementation/h_SDI-12_slave_implementation.ino
@@ -206,6 +206,9 @@
         // '!' should be the last available character anyway, but exit the "for" loop
         // just in case there are any stray characters
         slaveSDI12.clearBuffer();
+        //to eliminate the chance to sense anoter information from outsite with
+        //the interrupt pin - set as hold and continue to code
+        slaveSDI12.forceHold();
         break;
       }
       // If the current character is anything but '!', it is part of the command
@@ -230,6 +233,7 @@
       // Populate the "dValues" String array with the values in SDI-12 format
       formatOutputSDI(measurementValues, dValues, 75);
       state = WAIT;
+      slaveSDI12.forceListen();  // sets SDIPIN as input to prepare for incoming message AGAIN
       break;
     case INITIATE_MEASUREMENT:
       // Do whatever the sensor is supposed to do here
@@ -242,6 +246,7 @@
       // For aM!, Send "service request" (<address><CR><LF>) when data is ready
       slaveSDI12.sendResponse(String(sensorAddress) + "\r\n");
       state = WAIT;
+      slaveSDI12.forceListen();  // sets SDIPIN as input to prepare for incoming message AGAIN
       break;
   }
 }


Changed Telnet Port to port 23

Changed Telnet Port to port 23

Best to stick to standard port numbers
https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers

--- libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino
+++ libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino
@@ -25,7 +25,7 @@
 const char* ssid = "**********";
 const char* password = "**********";

-WiFiServer server(21);
+WiFiServer server(23);
 WiFiClient serverClients[MAX_SRV_CLIENTS];

 void setup() {
@@ -45,7 +45,7 @@

   Serial1.print("Ready! Use 'telnet ");
   Serial1.print(WiFi.localIP());
-  Serial1.println(" 21' to connect");
+  Serial1.println(" 23' to connect");
 }

 void loop() {


Renamed vars to match their lights in the xmas landscape

--- src/LegoChristmasTrain.ino
+++ src/LegoChristmasTrain.ino
@@ -5,12 +5,18 @@

 PowerFunctions pf(5, 0);
 LegoTrain train(pf, 4);
-CandleLED ledOne(6);
+CandleLED lampPostAndReindeer(6, CANDLE, 0.1);
+CandleLED fire(9, FIRE, 1.0);
+CandleLED twinLights(11, CANDLE, 0.1);
+CandleLED upperFloorAndLight(10, CANDLE, 0.3);

 void setup() {
 }

 void loop() {
   train.update();
-  ledOne.update();
+  lampPostAndReindeer.update();
+  fire.update();
+  twinLights.update();
+  upperFloorAndLight.update();
 }


Modify: Fix motor stop and on.

Modify: Fix motor stop and on.

--- arduino/DC_motor_CAN/DC_motor_CAN.ino
+++ arduino/DC_motor_CAN/DC_motor_CAN.ino
@@ -13,8 +13,9 @@
 unsigned char rotate[8] =      {0x1C, 0x72, 0x00, 0x01, 0x00, 0x00, 0x50, 0x41};
 unsigned char st[8] =          {0x1C, 0x72, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00};

-unsigned char motor_1_on[6] =  {0x14, 0x65, 0x00, 0x01, 0x00, 0x01};
-unsigned char motor_1_off[8] = {0x14, 0x65, 0x00, 0x01, 0x00, 0x00};
+unsigned char motor_1_on[8] =  {0x14, 0x65, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00};
+unsigned char motor_1_off[8] = {0x14, 0x65, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00};
+
 unsigned char motor_1_quick_stop[6] = {0x14, 0x65, 0x00, 0x01, 0x00, 0x07};

 int statement_flag = 1;
@@ -49,6 +50,14 @@
       CAN.sendMsgBuf(0x01, 0, 8, st);
       Serial.println(statement_flag);
       break;
+    case 2:
+      CAN.sendMsgBuf(0x01, 0, 8, motor_1_on);
+      Serial.println(statement_flag);
+      break;
+    case 3:
+      CAN.sendMsgBuf(0x01, 0, 8, motor_1_off);
+      Serial.println(statement_flag);
+      break;
   }
   delay(100);
 }


added serial number to each /status message from motor to server

--- arduino/motor_driver/motor_driver.ino
+++ arduino/motor_driver/motor_driver.ino
@@ -114,6 +114,9 @@

 EthernetUDP UDP;
 OscUDP etherOSC;
+
+// message serial numbers to check for missing ones
+int messageNumber = 0;

 int MSEC_PER_STATUS = 50; // millseconds between sending status messages

@@ -493,6 +496,9 @@
   msg.add(stepper);
   msg.add(encoder);

+  msg.add(messageNumber++);
+  if (messageNumber > 32000) messageNumber = 0;
+
   etherOSC.send(msg, destination);
 }

@@ -514,8 +520,9 @@

 void oscGo(OscMessage &m) {
-  // /go/motor0pos,motor1pos,motor2pos,motor3pos long ints
+  // /go/motor0pos,motor1pos,motor2pos,motor3pos floats
   if (state != OK) return;
+  if (m.size() < 4) return;

   double value = m.getFloat(MOTOR_ID);
   pidSetpoint = value;


fix code

fix code

--- little-switches/arduino/3_setup-rel/3_setup-rel.ino
+++ little-switches/arduino/3_setup-rel/3_setup-rel.ino
@@ -33,14 +33,14 @@
   pinMode(A0,OUTPUT);
   pinMode(A1,OUTPUT);

-  digital(2,OUTPUT);
-  pinMode(4,OUTPUT);
-  pinMode(5,OUTPUT);
-  pinMode(6,OUTPUT);
-  pinMode(7,OUTPUT);
-  pinMode(8,OUTPUT);
-  pinMode(A0,OUTPUT);
-  pinMode(A1,OUTPUT);
+  digitalWrite(2,LOW);
+  digitalWrite(4,LOW);
+  digitalWrite(5,LOW);
+  digitalWrite(6,LOW);
+  digitalWrite(7,LOW);
+  digitalWrite(8,LOW);
+  digitalWrite(A0,LOW);
+  digitalWrite(A1,LOW);

 }