Update mqtt_dragino_2xrele_lcd_20x4_serial_i2c_ver2.ino

--- dragino/mqtt_dragino_2xrele_lcd_20x4_serial_i2c_ver2.ino
+++ dragino/mqtt_dragino_2xrele_lcd_20x4_serial_i2c_ver2.ino
@@ -63,8 +63,8 @@

-   mqtt.publish("/pryxo/yxusers/lrojas/control/ui98h23d09h2d/rele/1",estadorele1);
-   mqtt.publish("/pryxo/yxusers/lrojas/control/ui98h23d09h2d/rele/2",estadorele2);
+   mqtt.publish("/pryxo/yxusers/98h23d09h2d/rele/1",estadorele1);
+   mqtt.publish("/pryxo/yxusers/98h23d09h2d/rele/2",estadorele2);
 /*lcd.home();
   lcd.setCursor(0,2);
   lcd.print("Status RELE 1X:");


Fixed sensor label updating.

Fixed sensor label updating.

--- tfttask.ino
+++ tfttask.ino
@@ -256,15 +256,15 @@
     drawSensors( true );
   }

-  struct savedSensor_t
-  {
-    char name[ sizeof( sensor->name ) ];
-  };
-
-  savedSensor_t savedSensor[numberOfFoundSensors];
-
   if ( numberOfFoundSensors && !tftClearScreen )
   {
+    struct savedSensor_t
+    {
+      char name[ sizeof( sensor->name ) ];
+    };
+
+    static savedSensor_t savedSensor[MAX_NUMBER_OF_SENSORS];
+
     for ( auto thisSensor = 0; thisSensor < numberOfFoundSensors; thisSensor++ )
     {
       if ( strcmp( sensor[thisSensor].name, savedSensor[thisSensor].name ) != 0 )


Modified Keyboard Reprogram example

Modified Keyboard Reprogram example

Updated to reflect changes with how the IDE creates new blank sketches.

--- build/shared/examples/09.USB/Keyboard/KeyboardReprogram/KeyboardReprogram.ino
+++ build/shared/examples/09.USB/Keyboard/KeyboardReprogram/KeyboardReprogram.ino
@@ -11,12 +11,14 @@
  a final key combination (CTRL-U).

  Circuit:
- * Arduino Leonardo or Micro
+ * Arduino Leonardo, Micro, Due, LilyPad USB, or Yun
  * wire to connect D2 to ground.

  created 5 Mar 2012
  modified 29 Mar 2012
  by Tom Igoe
+ modified 3 May 2014
+ by Scott Fitzgerald

  This example is in the public domain

@@ -53,6 +55,18 @@
   Keyboard.releaseAll();
   // wait for new window to open:
   delay(1000);
+
+  // versions of the Arduino IDE after 1.5 pre-populate
+  // new sketches with setup() and loop() functions
+  // let's clear the window before typing anything new
+  //  select all
+  Keyboard.press(ctrlKey);
+  Keyboard.press('a');
+  delay(500);
+  Keyboard.releaseAll();
+  // delete the selected text
+  Keyboard.write(KEY_BACKSPACE);
+  delay(500);

   // Type out "blink":
   Keyboard.println("void setup() {");
@@ -93,3 +107,4 @@

+


String example in TURIPonUARTserver_GPIO

--- TURIPshell/examples/TURIPonUARTserver_GPIO/TURIPonUARTserver_GPIO.ino
+++ TURIPshell/examples/TURIPonUARTserver_GPIO/TURIPonUARTserver_GPIO.ino
@@ -21,6 +21,7 @@
 TURIPport* aIn2;
 TURIPport* aOut1;
 TURIPport* aOut2;
+TURIPport* strPort;

 void setup(){
   Serial.begin(9600);
@@ -41,6 +42,7 @@
   aIn2 = TURIPserver.newPort(6);
   aOut1 = TURIPserver.newPort(7);
   aOut2 = TURIPserver.newPort(8);
+  strPort = TURIPserver.newPort(10);

   dIn1->writeUint16(0);
   dIN2->writeUint16(0);
@@ -50,6 +52,7 @@
   aIn2->writeUint16(0);
   aOut1->writeUint16(0);
   aOut2->writeUint16(0);
+  strPort->writeString(String("This is GPIO server."));

   aIn1->preTransmitFunc = setValues;
   aIn2->preTransmitFunc = setValues;


Changes so the example will work with particle.io

--- firmware/examples/JsonStreamingParser.ino
+++ firmware/examples/JsonStreamingParser.ino
@@ -1,100 +0,0 @@
-/*
-Because sometimes, you just can't parse json via a webhook.
-
-This library is a modified fork of squix78's json-streaming-parser an Arduino library for parsing potentially huge json
-streams on devices with scarce memory.
-
-Changes from squix78's version:
-
-1) Layout changed so it could be deployed as a particle library.
-2) Only one startDocument will be raised at the start of a document rather than one for each non-json character.
-3) Keys are now passed to the listener as part of the startObject(), startArray() or value() event they are associated
-   with rather than as seperate events.
-
-How to use
-----------
-
-This is a streaming parser, which means that you feed a stream of chars into the parser and you take out from that
-stream whatever you are interested in. In order to do that you will create a subclass of JsonListener class and
-implement methods which will be notified in case of certain events in the feed occure. Available events are:
-
-startDocument()
-endDocument()
-
-startObject(String key)
-endObject()
-
-startArray(String key)
-endArray()
-
-value(String key, String value)
-
-In your implementation of these methods you will have to write problem specific code to find the parts of the
-document that you are interested in. Please see the example to understand what that means. In the example the
-ExampleListener implements the event methods declared in the JsonListener interface and prints to the serial
-console when they are called.
-
-*/
-
-
-#include "JsonStreamingParser/JsonStreamingParser.h"
-#include "JsonStreamingParser/JsonListener.h"
-
-class ExampleListener: public JsonListener {
-
-  public:
-    void whitespace(char c) {
-        Serial.println("whitespace");
-    }
-
-    void value(String key, String value) {
-      Serial.print("key: " + key + ", ");
-      Serial.println("value: " + value);
-    }
-
-    void startDocument() {
-      Serial.println("start document");
-    }
-
-    void endDocument() {
-      Serial.println("end document. ");
-    }
-
-    void startArray(String key) {
-       Serial.print("start array: ");
-       Serial.println(key);
-    }
-
-    void endArray() {
-      Serial.println("end array. ");
-    }
-
-    void startObject(String key) {
-       Serial.print("start object:");
-       Serial.println(key);
-    }
-
-    void endObject() {
-      Serial.println("end object. ");
-    }
-};
-
-JsonStreamingParser parser;
-ExampleListener listener;
-
-void setup() {
-  Serial.begin(9600);
-  // Wait for a character on the serial port.  Connect with a terminal emulator and press any key to see the output
-  while(!Serial.available()) Particle.process();
-  Serial.println(System.freeMemory());
-  parser.setListener(&listener);
-  // put your setup code here, to run once:
-  char json[] = "{\"a\":3, \"b\":{\"c\":\"4\"}, \"e\":[{\"f\":5},{\"g\":6}]}";
-  for (int i = 0; i < sizeof(json); i++) {
-    parser.parse(json[i]);
-  }
-  Serial.println(System.freeMemory());
-}
-
-void loop() {
-}


Voltage alarm bugfix

Voltage alarm bugfix

--- KISS_OSD/KISS_OSD.ino
+++ KISS_OSD/KISS_OSD.ino
@@ -896,17 +896,14 @@
           }
         }

-        if(settings.m_voltWarning > 0 && settings.m_minVolts > (LipoVoltage / 10))
-        {
-          if(timer1sec)
-          {
-            OSD.printInt16(settings.COLS/2 - 3, settings.ROWS/2 + 2, LipoVoltage / 10, 1, 1, "v", 1);
-          }
-          else
-          {
-            OSD.setCursor(settings.COLS/2 - 3, settings.ROWS/2 + 2);
-            OSD.printSpaces(5);
-          }
+        if(settings.m_voltWarning > 0 && settings.m_minVolts > (LipoVoltage / 10) && !timer1sec)
+        {
+          OSD.printInt16(settings.COLS/2 - 3, settings.ROWS/2 + 2, LipoVoltage / 10, 1, 1, "v", 1);
+        }
+        else
+        {
+          OSD.setCursor(settings.COLS/2 - 3, settings.ROWS/2 + 2);
+          OSD.printSpaces(5);
         }

         if(DV_change_time > 0 && (millis() - DV_change_time) > 3000 && last_Aux_Val == AuxChanVals[settings.m_DVchannel])


Final "old version"

Final "old version"

Will refactor to parsing input strings instead of chopping input into
triplets; this will allow for more complicated commands (e.g.
"GRAD000000:FFFFFF", etc.).

--- csarc/csarc.ino
+++ csarc/csarc.ino
@@ -5,6 +5,8 @@
 RGBdriver Driver(CLK,DIO);
 static int BAUDRATE = 9600;
 int red,green,blue;
+int* rbg[3] = {&red, &green, &blue};
+// probably actually learn about pointers before using this, but it'd make some things simpler.

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


Fixed no response from 'api/pwmfrequency'.

No response from getting the PWMfrequency.

--- webserver.ino
+++ webserver.ino
@@ -136,8 +136,8 @@
       }
       PWMfrequency = tempPWMfrequency;
       analogWriteFreq( PWMfrequency );
-      webServer.send( 200, "text/plain", "PWM frequency is " + String( tempPWMfrequency ) );
-    }
+    }
+    webServer.send( 200, "text/plain", "PWM frequency is " + String( PWMfrequency ) );
   });

   webServer.on( "/api/pwmdepth", []() {


More work on time query

More work on time query

--- Arduino_HVAC_Controller/Networked_HVAC_Controller/Networked_HVAC_Controller.ino
+++ Arduino_HVAC_Controller/Networked_HVAC_Controller/Networked_HVAC_Controller.ino
@@ -140,7 +140,7 @@
 // ----------------------------------------------------------------------------------------
 void setup(){

-  setup_Network();           // Do all the things necessary to get the network protocol going
+  setup_network();           // Do all the things necessary to get the network protocol going

   // --------------- Relay Setup ---------------
   pinMode(heatPin,OUTPUT);   // Heat circuit relay
@@ -171,6 +171,9 @@
 // Description:   This is the main executing block of the program, calling all ancillary functions to operate the Arduino
 // ----------------------------------------------------------------------------------------
 void loop(){
+
+  setup_time();
+
   if ((millis() - timeOut) > 30000) {   // Turn on backlight for 30 seconds, else turn it off
     lcd.setBacklight(OFF);
     editable == FALSE;
@@ -183,7 +186,7 @@
   uint8_t buttons = lcd.readButtons();  // Constantly check to see if something has been put on the bus

   // --------------Handle updating Temp Change Display---------------------
-  if (getTemp()) {                      // Constantly check to see if the temperature has changed, and update appropriately
+  if (get_temp()) {                      // Constantly check to see if the temperature has changed, and update appropriately
     lcd.clear();
     lcd.print("Current Temp: ");
     lcd.print(currentTemp);
@@ -198,23 +201,23 @@
     if (buttons & BUTTON_SELECT) {      // Allow parameters to be changed only if the Select button has been pressed first
       editable = TRUE;
     }
-    if (editable) {                     // go to buttonHandler to handle menu switching and parameter manipulations
-      buttonHandler(buttons);
+    if (editable) {                     // go to button_handler to handle menu switching and parameter manipulations
+      button_handler(buttons);
     }
   }

   // --------------Handle Heat and Cooling Cycles---------------------
-  powerControl();
-
-}
-
-// ----------------------------------------------------------------------------------------
-// Function Name: powerControlHandler()
+  power_control();
+
+}
+
+// ----------------------------------------------------------------------------------------
+// Function Name: power_controlHandler()
 // Parameters:    None
 // Returns:       None
 // Description:   This function will handle turning AC or Heat off and on based on current temp, timers, and setpoints
 // ----------------------------------------------------------------------------------------
-void powerControl(){
+void power_control(){

   // TODO: __________________________Add in fan relay control____________________

@@ -256,12 +259,12 @@

 // ----------------------------------------------------------------------------------------
-// Function Name: buttonHandler()
+// Function Name: button_handler()
 // Parameters:    None
 // Returns:       Boolean, True if the temperature has changed, else False
 // Description:   This function polls the temp sensors, retrieves the values, and then returns
 // ----------------------------------------------------------------------------------------
-boolean buttonHandler(uint8_t buttons){
+boolean button_handler(uint8_t buttons){

   // --------------PARAMETERS---------------------
   int heatModifier = 0;
@@ -329,19 +332,19 @@
 }

 // ----------------------------------------------------------------------------------------
-// Function Name: getTemp()
+// Function Name: get_temp()
 // Parameters:    None
 // Returns:       Boolean, True if the temperature has changed, else False
 // Description:   This function polls the temp sensors, retrieves the values, and then returns
 // ----------------------------------------------------------------------------------------
-boolean getTemp(){
+boolean get_temp(){
   currentTemp = 0;
   long temp = 0;
   sensors.requestTemperatures(); // Send the command to the device to get temperatures

   // Go through devices and read the temperatures
   for(int x = 0; x < numOfDevices; x++){
-    temp = sensors.getTempF(addrs[x]);
+    temp = sensors.get_tempF(addrs[x]);
     if(temp != currentTemp){
       currentTemp = temp;
     }
@@ -359,12 +362,12 @@

 // ----------------------------------------------------------------------------------------
-// Function Name: setup_Network()
+// Function Name: setup_network()
 // Parameters:    None
 // Returns:       None
 // Description:   This function does all the prep work to create a network connection
 // ----------------------------------------------------------------------------------------
-void setup_Network() {
+void setup_network() {

   // TODO: _________________________REMOVE ALL Serial stuff when it works________________________

@@ -385,4 +388,88 @@
   Udp.begin(localPort);
 }

-
+// ----------------------------------------------------------------------------------------
+// Function Name: get_time()
+// Parameters:    None
+// Returns:       None
+// Description:   TODO ____________________________________________________
+// ----------------------------------------------------------------------------------------
+void get_time()
+{
+  sendNTPpacket(timeServer); // send an NTP packet to a time server
+
+    // wait to see if a reply is available
+  delay(1000);
+  if ( Udp.parsePacket() ) {
+    // We've received a packet, read the data from it
+    Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read the packet into the buffer
+
+    //the timestamp starts at byte 40 of the received packet and is four bytes,
+    // or two words, long. First, esxtract the two words:
+
+    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
+    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
+    // combine the four bytes (two words) into a long integer
+    // this is NTP time (seconds since Jan 1 1900):
+    unsigned long secsSince1900 = highWord << 16 | lowWord;
+    Serial.print("Seconds since Jan 1 1900 = " );
+    Serial.println(secsSince1900);
+
+    // now convert NTP time into everyday time:
+    Serial.print("Unix time = ");
+    // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
+    const unsigned long seventyYears = 2208988800UL;
+    // subtract seventy years:
+    unsigned long epoch = secsSince1900 - seventyYears;
+    // print Unix time:
+    Serial.println(epoch);
+
+
+    // print the hour, minute and second:
+    Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
+    Serial.print((epoch  % 86400L) / 3600); // print the hour (86400 equals secs per day)
+    Serial.print(':');
+    if ( ((epoch % 3600) / 60) < 10 ) {
+      // In the first 10 minutes of each hour, we'll want a leading '0'
+      Serial.print('0');
+    }
+    Serial.print((epoch  % 3600) / 60); // print the minute (3600 equals secs per minute)
+    Serial.print(':');
+    if ( (epoch % 60) < 10 ) {
+      // In the first 10 seconds of each minute, we'll want a leading '0'
+      Serial.print('0');
+    }
+    Serial.println(epoch %60); // print the second
+  }
+  // wait ten seconds before asking for the time again
+  delay(10000);
+}
+
+// ----------------------------------------------------------------------------------------
+// Function Name: sendNTPpacket(IPAddress& address)
+// Parameters:    IP Address
+// Returns:       Unsigned Long
+// Description:   send an NTP request to the time server at the given address
+// ----------------------------------------------------------------------------------------
+unsigned long sendNTPpacket(IPAddress& address)
+{
+  // set all bytes in the buffer to 0
+  memset(packetBuffer, 0, NTP_PACKET_SIZE);
+  // Initialize values needed to form NTP request
+  // (see URL above for details on the packets)
+  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
+  packetBuffer[1] = 0;     // Stratum, or type of clock
+  packetBuffer[2] = 6;     // Polling Interval
+  packetBuffer[3] = 0xEC;  // Peer Clock Precision
+  // 8 bytes of zero for Root Delay & Root Dispersion
+  packetBuffer[12]  = 49;
+  packetBuffer[13]  = 0x4E;
+  packetBuffer[14]  = 49;
+  packetBuffer[15]  = 52;
+
+  // all NTP fields have been given values, now
+  // you can send a packet requesting a timestamp:
+  Udp.beginPacket(address, 123); //NTP requests are to port 123
+  Udp.write(packetBuffer,NTP_PACKET_SIZE);
+  Udp.endPacket();
+}


Robot can observe and avoid solid walls

Robot can observe and avoid solid walls

--- iso/carl_breadboard/carl_breadboard.ino
+++ iso/carl_breadboard/carl_breadboard.ino
@@ -4,6 +4,8 @@
 #define MOTORPIN1A A1 //motor 1 pin A
 #define MOTORPIN2A A2 //motor 2 pin A
 #define MOTORPIN2B A3 //motor 2 pin B
+#define TRIGPIN 6 //ultrasonic trigger pin
+#define ECHOPIN 7 //ultrasonic echo pin

 unsigned long int loopIter=0;

@@ -12,12 +14,47 @@
 	Serial.println();
 	pinMode(LINEPIN1, INPUT);
 	pinMode(LINEPIN2, INPUT);
+	pinMode(ECHOPIN, INPUT);
+	pinMode(TRIGPIN, OUTPUT);
 }

 int pleft=0;
 int pright=1;
 void loop() {
+
+	//checkLines();
+	checkUltrasonic();
+}
+
+int getUltrasonic() {
+	long duration, cm;
+	digitalWrite(TRIGPIN, LOW);
+	delayMicroseconds(2);
+	digitalWrite(TRIGPIN, HIGH);
+	delayMicroseconds(10);
+	digitalWrite(TRIGPIN, LOW);
+	duration = pulseIn(ECHOPIN, HIGH); //duration is now a value in milliseconds of how long it took for a sound wave to exit the sensor, and bounce off of an object back into the sensor
+	cm = duration / 34 / 2; //using the speed of sound, we find distance from object infront of us. look up "basic kinematics : finding distance using velocity and time"
+	int distance = (int)cm;
+	return distance;
+}
+
+void checkUltrasonic() { //check distance infront of ultrasonic sensor
+	int distance = getUltrasonic();
+	Serial.print("DIST ");
+	Serial.println(distance);
+	//Distances over 16 are irrelevant
+	if (distance<10) {
+		Serial.print("odear");
+		motor_SetOutputs(500,0,0,500);
+		delay(750);
+	} else {
+		motor_SetOutputs(0,500,0,500);
+	}
+}
+
+void checkLines() {
 	int right = digitalRead(LINEPIN1);
 	int left = digitalRead(LINEPIN2);
 	int nleft=0;
@@ -40,24 +77,23 @@
 		pleft=0;
 	}
 	motor_SetOutputs(nleft,aleft,nright,aright );
-	Serial.print(pleft);
-	Serial.print(" ");
-	Serial.print(pright);
-	Serial.print(" ");
-	Serial.print(left);
-	Serial.print(" ");
-	Serial.print(right);
-	Serial.print(" ");
-	Serial.print(aleft);
-	Serial.print(" ");
-	Serial.print(aright);
-	Serial.println(" ");
-	motor_SetOutputs(nleft,aleft,nright,aright );
-
+	// Serial.print(pleft);
+	// Serial.print(" ");
+	// Serial.print(pright);
+	// Serial.print(" ");
+	// Serial.print(left);
+	// Serial.print(" ");
+	// Serial.print(right);
+	// Serial.print(" ");
+	// Serial.print(aleft);
+	// Serial.print(" ");
+	// Serial.print(aright);
+	// Serial.println(" ");
+	motor_SetOutputs(nleft,aleft,nright,aright);
 }

 void motor_SetOutputs(int apina, int apinb, int bpina, int bpinb) {
- 	analogWrite(MOTORPIN1A, apina);
+	analogWrite(MOTORPIN1A, apina);
 	analogWrite(MOTORPIN1B, apinb);
 	analogWrite(MOTORPIN2A, bpina);
 	analogWrite(MOTORPIN2B, bpinb);


corrections in OLED code

corrections in OLED code

implement DRAW_CIRCLE command
correct counter for graphics string to have 16 bit offsets (command chain longer than 256 bytes)
remove examples, backslash as string terminator messed up C code

--- ksp-gegi-microusb/ksp-gegi-microusb.ino
+++ ksp-gegi-microusb/ksp-gegi-microusb.ino
@@ -182,6 +182,9 @@
 // serial port
 #define SERIAL_SPEED 115200

+// used below
+void oledRedraw();
+
 void setup() {
   // initialize serial communications
   Serial.begin(SERIAL_SPEED);
@@ -260,12 +263,13 @@
 #define OLED_DRAW_HLINE 5 // followed by x y width
 #define OLED_DRAW_VLINE 6 // followed by x y height
 #define OLED_DRAW_LINE  7 // followed by x1 y1 x2 y2
+#define OLED_DRAW_CIRCLE 8 // followed by x y radius

 void drawOLED(void) {
   // graphic commands to redraw the complete screen should be placed here
   u8g.setFont(u8g_font_unifontr); // reduced font, only glyphs 0x20-0x7f
-  uint8_t i=0;
-  uint8_t cmd, x, y, w, h, x2, y2;
+  uint16_t i=0;
+  uint8_t cmd, x, y, w, h, x2, y2, radius;
   while ((i<OLEDBUFSIZE) && oledBuf[i]!=0) {
     cmd = oledBuf[i++];
     if (OLED_DRAW_STOP==cmd) break; // stop immediately if commanded
@@ -309,16 +313,18 @@
 //          Serial.print("x2="); Serial.print(x2); Serial.print(" y2="); Serial.println(y2);
           u8g.drawLine(x,y,x2,y2);
           break;
+        case OLED_DRAW_CIRCLE:
+          radius = oledBuf[i++];
+//          Serial.print("rad="); Serial.println(radius);
+          u8g.drawCircle(x,y,radius);
+          break;
     }
   }
 }

 // read a string of gfx commands and keep them in a buffer so drawOLED() can use them
-// test:
-// O3 0 0 10 16 3 10 0 10 24 3 0 16 127 16 4 23 23 5 15 55 100 6 64 15 70 7 15 15 120 90 1 0 16 Line1\ 1 0 32 Line2\ 1 0 48 Line3\ 7 120 15 15 90
-// O7,128,0,0,15,7,128,0,32,15,7,128,0,64,15,7,128,64,0,48,7,128,64,32,48,7,128,64,64,48,1,0,32,KSP\,1,0,48,Ready\
 void handleSerialInputOLED() {
-  uint8_t i=0;
+  uint16_t i=0;
   uint8_t cmd, c;
 //  Serial.println("OLEDstart");
   while ((i<OLEDBUFSIZE) && (Serial.available()>0) && (Serial.peek()!= '\n')) {
@@ -343,6 +349,7 @@
           oledBuf[i++] = Serial.parseInt(); // read two more bytes (one here, one below)
         case OLED_DRAW_HLINE:
         case OLED_DRAW_VLINE:
+        case OLED_DRAW_CIRCLE:
           oledBuf[i++] = Serial.parseInt(); // read one more byte
         case OLED_DRAW_STOP:
         case OLED_DRAW_PIXEL:


test : keep alive, serial out

test : keep alive, serial out

mqtt keep alive to 5 sec from 15 sec
reconnect to 1 sec from 5sec
serial begin to 115200 from none(74880)

--- _04-lcd-dust/_04-mqtt-lcd-dust-sensor-esp-12/_04-mqtt-lcd-dust-sensor-esp-12.ino
+++ _04-lcd-dust/_04-mqtt-lcd-dust-sensor-esp-12/_04-mqtt-lcd-dust-sensor-esp-12.ino
@@ -18,7 +18,7 @@

 RtcDS3231 Rtc;

-#define DEBUG_PRINT 0
+#define DEBUG_PRINT 1

 char* topic = "esp8266/arduino/s03";
 char* subtopic = "#";
@@ -389,8 +389,9 @@
   delay(50);

   if (DEBUG_PRINT) {
-    Serial.begin(74880);
-    Serial.setDebugOutput(true);
+    Serial.begin(115200);
+    //Serial.begin(74880);
+    //Serial.setDebugOutput(true);
   }

   startMills = millis();
@@ -582,7 +583,7 @@
         Serial.println(client.state());
       }
       long now = millis();
-      if (now - lastReconnectAttempt > 5000) {
+      if (now - lastReconnectAttempt > 1000) {
         lastReconnectAttempt = now;
         if (reconnect()) {
           lastReconnectAttempt = 0;


Got key presses working with detection of long key presses

--- arduino/libraries/ClockTiM/examples/ClockTiM/ClockTiM.ino
+++ arduino/libraries/ClockTiM/examples/ClockTiM/ClockTiM.ino
@@ -1,20 +1,25 @@
+

 #include <avr/pgmspace.h>
-//#include <TimerOne.h>
 #include <Time.h>
 #include "english_v2.h"

-#define TiMPIN			A0
-#define BUTTON_L		A1
-#define BUTTON_R		A2
+#define TiMPIN				A0
+#define BUTTON_L			8
+#define BUTTON_R			12
+#define PIN_LOW				10

-#define BUTTON_L_IDX	1
-#define BUTTON_R_IDX	2
+#define BUTTON_L_IDX		1
+#define BUTTON_R_IDX		2

-/*// Stores the current time, in half-seconds, since the beginning of the day.
-uint16_t g_time2Hz = 0;
-uint16_t g_time1Hz = 0;
-uint16_t g_timeMinutes = 0;*/
+#define LONG_PRESS_MILLIS	2000
+
+typedef struct KeyStates{
+	uint8_t justPressed;	// Buttons that have just been pressed
+	uint8_t longPressed;	// Buttons that have been pressed for a long time
+	uint8_t up;				// Buttons that are pressed
+	uint8_t down;			// Buttons that are released
+};

 void setup() {
 	// Setup the GPIO
@@ -23,37 +28,63 @@
 	pinMode(BUTTON_R, INPUT);
 	digitalWrite(BUTTON_R, HIGH);

+	pinMode(PIN_LOW, OUTPUT);
+	digitalWrite(PIN_LOW, LOW);
+
 	// Start the serial port
 	Serial.begin(9600);

 	// Initialise the display
 	disp_init();
-
-/*	// Interrupt timer 1 every 1/2 a second
-	Timer1.initialize(500000);
-	Timer1.attachInterrupt(twiceASecond);*/
 }

 void loop() {
+	static int prev_sec = second();
+	static int prev_min = minute();
+	int sec;
+	int min;
+
 	uint16_t ledStates[8] = { 0 };
-	uint8_t keys;
+	KeyStates *keys = NULL;

 	keys = getKeys();

 	// Depending on the keys just pressed, take the necessary action
+	switch(keys->longPressed) {
+	case BUTTON_L_IDX:
+		Serial.println("Pressed left a long time");
+		break;
+	case BUTTON_R_IDX:
+		Serial.println("Pressed right a long time");
+		break;
+	case BUTTON_L_IDX | BUTTON_R_IDX:
+		Serial.println("Pressed left and right a long time");
+		break;
+	default:
+		break;
+	}

-	displayWord(ledStates, g_timeMinutes >> 1);
+	sec = second();
+	min = minute();
+	if(prev_sec != sec) {
+		if(prev_min != min) {
+			int totalMinutes = (hour() * 60) + min;
+			displayWord(ledStates, totalMinutes / 5);
+			prev_min = min;
+		}

-	// Make the bottom right LED blink every second
-	ledStates[7] |= second() & 0x01;
+		// Make the bottom right LED blink every second
+		ledStates[7] |= sec & 0x01;
+		prev_sec = sec;

-	disp_display(ledStates);
+		disp_display(ledStates);
+	}
 }

 void displayWord(uint16_t *ledStates, int time) {
 	// Loop through every line
-	Serial.print("Time: ");
-	Serial.println(time);
+//	Serial.print("Time: ");
+//	Serial.println(time);

 	for(int dispIdx = 0; dispIdx < 4; dispIdx++) {

@@ -82,15 +113,15 @@
 }

 // Returns a byte with the idx of any newly pressed keys set to '1'. Also includes debouncing.
-uint8_t getKeys() {
+struct KeyStates *getKeys() {
 	static uint8_t debounce[4];			// Stores the queue of the push button states
 	static uint8_t debounceIdx = 0;		// Stores the index we are current at within the debounce queue
-	static uint8_t buttons;				// Stores the state of the buttons
+	static uint8_t states;				// Stores the state of the keys
+	static long timeInStates = 0;		// Records the amount of time <states> has been in its current state

-	uint8_t prevButtons;				// Temp variable used for comparison with previous button states
+	static KeyStates keys;
+
 	uint8_t pressed = 0;				// Holds which buttons are currently pressed
-	uint8_t up;							// Indicates which buttons have been pressed for a long time
-	uint8_t down;						// Indicates which buttons have been released for a long time

 	if(digitalRead(BUTTON_L) == LOW) {
 		pressed |= BUTTON_L_IDX;
@@ -103,19 +134,28 @@
 	debounce[debounceIdx++] = pressed;
 	debounceIdx &= 3;

-	down = debounce[0] & debounce[1] & debounce[2] & debounce[3];
-	up = debounce[0] | debounce[1] | debounce[2] | debounce[3];
+	keys.down = debounce[0] & debounce[1] & debounce[2] & debounce[3];
+	keys.up = debounce[0] | debounce[1] | debounce[2] | debounce[3];

 	// Determine which buttons have freshly been pressed and return the result
-	prevButtons = buttons;
-	buttons &= up;
-	buttons |= down;
-	return buttons & (buttons ^ prevButtons);
+	uint8_t prevStates = states;
+	states &= keys.up;
+	states |= keys.down;
+	keys.justPressed = states & (states ^ prevStates);
+
+	if(states != 0) {
+		if(states != prevStates) {
+			timeInStates = millis();
+		} else {
+			if(millis() - timeInStates > LONG_PRESS_MILLIS) {
+				keys.longPressed = keys.up;
+			}
+		}
+	} else {
+		keys.longPressed = 0;
+	}
+
+	return &keys;
 }

-/*void twiceASecond() {
-	g_time2Hz++;
-	g_time1Hz = g_time2Hz >> 1;
-	g_timeMinutes = g_time1Hz % 60;
-}*/


Fix order of Serial.println arguments for HEX printing

--- zg01/zg01.ino
+++ zg01/zg01.ino
@@ -41,7 +41,7 @@
     // process data if ready
     if (ready) {
         for (int i = 0; i < 5; i++) {
-            Serial.print(HEX, buffer[i]);
+            Serial.print(buffer[i], HEX);
             Serial.print(" ");
         }
         Serial.println();


refactored master

refactored master

--- src/BigRedButton/BigRedButton.ino
+++ src/BigRedButton/BigRedButton.ino
@@ -34,6 +34,8 @@
 int buttonState = 0;
 int requestMade = 0;

+boolean wifiReady = false;
+
 // initialise the WiFly card
 WiFlySerial WiFly(ardRxPin, ardTxPin);

@@ -44,95 +46,136 @@
  */
 void setup()
 {
-  // initialise card
+    Serial.begin(9600);
     delay(2000);
-    Serial.begin(9600);
     Serial.println("THE BUTTON");
-
+
+    // we'll keep the LED off until we can press the button
     pinMode(ledPin, OUTPUT);
-    // we'll keep the LED off until we can press the button
     digitalWrite(ledPin, LOW);

+    // initialise a session with the wifi card
     WiFly.begin();
-   //WiFly.reboot();
+
     // get MAC address
     Serial << F("MAC: ") << WiFly.getMAC(bufRequest, REQUEST_BUFFER_SIZE) << endl;

+    // and join our network
+    Serial << F("No button pressed - attempting association") << endl;
+    wifiJoin();
+}
+
+/**
+ * Main loop - waiting for a button press
+ * Indicates status through the LED:
+ *  - solid LED: network available and button ready
+ *  - slow flashing: network unavailable
+ */
+void loop()
+{
+    // only execute the loop if wifi is available
+    if(wifiReady == 1) {
+
+        // read the state of the button
+        buttonState = digitalRead(buttonPin);
+
+        // HIGH == pressed
+        if (buttonState == HIGH) {
+
+            // if a request is in progress, ignore
+            // additional button presses
+            if(requestMade == 0) {
+
+                // make the request
+                requestMade = 1;
+                request();
+
+            } else {
+                //Serial.println("request already made");
+            }
+
+        } else {
+            requestMade = 0;
+            //Serial.println("button off");
+        }
+
+    } else {
+        // slow flash
+        flashLed(1, 2000);
+        // attempt reconnect
+        // wifiJoin();
+    }
+}
+
+/**
+ * Set the connection parameters for the wifi card
+ */
+void wifiSetParams()
+{
     // set our auth options
     WiFly.setAuthMode( WIFLY_AUTH_WPA2_PSK );
     WiFly.setJoinMode( WIFLY_JOIN_AUTO );
+
+    // enable DHCP
     WiFly.setDHCPMode( WIFLY_DHCP_ON );
+
     // use our expensive external antenna
     WiFly.setUseExternalAnt(WIFLY_EXTERNAL_ANT_ON);
-
+}
+
+/**
+ * Join a wifi network
+ */
+boolean wifiJoin()
+{
     Serial << F("Attempting to join network '") << wifiSSID << F("'...") << endl;
+
+    // set out auth options
+    wifiSetParams();
+
     // open link, if we don't already have one
     WiFly.getDeviceStatus();
-    if (! WiFly.isifUp() )
-    {
+    if (! WiFly.isifUp()) {
+
+        // leave any joined networks
         WiFly.leave();
-        // join
+
+        // join our network
         WiFly.setSSID(wifiSSID) ;
         WiFly.setPassphrase(wifiPassphrase);
-        if ( WiFly.join() )
-        {
+
+        // check that we managed to join
+        if (WiFly.join()) {
+
             Serial << F("We associated with ") << wifiSSID << F(" successfully.") << endl;
-
+
             // disable default *hello* bullshit
             WiFly.SendCommand("set comm remote 0",">", bufBody, BODY_BUFFER_SIZE);
             memset (bufBody,'\0',BODY_BUFFER_SIZE);
-
+
             // clear out prior requests.
             WiFly.flush();
-            while (WiFly.available())
-                WiFly.read();
-
+            while (WiFly.available()) {
+                WiFly.read();
+            }
+
             // we're ready for the button - switch the LED on
             digitalWrite(ledPin, HIGH);
+            wifiReady = true;
+
+        } else {
+            // could not join network
+            Serial << F("Association with ") << wifiSSID << F(" failed.") << endl;
+            wifiReady = false;
         }
-        else
-        {
-            Serial << F("Association with ") << wifiSSID << F(" failed.") << endl;
-        }
-    }
-    else
-    {
-            Serial << F("Network interface is not available") << endl;
-    }
-}
-
-/**
- * Main loop - waiting for a button press
- * Indicates status through the LED:
- *  - solid LED: network available and button ready
- */
-void loop()
-{
-    // read the state of the button
-    buttonState = digitalRead(buttonPin);
-    // HIGH == pressed
-    if (buttonState == HIGH)
-    {
-        Serial.println("button on");
-        // only make one request per press
-        if(requestMade == 0)
-        {
-            requestMade = 1;
-            // make the request
-            request();
-        }
-        else
-        {
-            Serial.println("request already made");
-        }
-    }
-    else
-    {
-        requestMade = 0;
-        //Serial.println("button off");
-    }
-}
-
+
+    } else {
+        Serial << F("Network interface is not available") << endl;
+        wifiReady = false;
+    }
+
+    return wifiReady;
+}

 /**
  * Make an HTTP GET request
@@ -142,7 +185,7 @@
     Serial.println("making request");
     char bufRequest[REQUEST_BUFFER_SIZE];

-    // Build request:
+    // Build request string. Request will look like:
     //" GET /v1.0/button HTTP/1.1\nHost: api.host.com\nConnection: close\n\n\n"
     PString strRequest(bufRequest, REQUEST_BUFFER_SIZE);
     strRequest << F("GET ") << serverGetUrl
@@ -156,40 +199,48 @@

     // Open connection, then send GET Request
     Serial << F("Opening connection to ") << serverHost << endl;
-    if (WiFly.openConnection( serverHost ) )
-    {
-
-        WiFly <<    strRequest << endl;
+    if (WiFly.openConnection(serverHost)) {
+
+        // send the request string to the server
+        WiFly << strRequest << endl;

         // buffer server response
         unsigned long TimeOut = millis() + 4000;

-        while (    TimeOut > millis() && WiFly.isConnectionOpen() )
-        {
-            if (    WiFly.available() > 0 )
-            {
-                // display
+        while (TimeOut > millis() && WiFly.isConnectionOpen()) {
+            if (WiFly.available() > 0) {
+                // display response
                 Serial << (char) WiFly.read();
             }
         }

         // Force close connection
         WiFly.closeConnection();
-
-        // force a 2 second delay
-        delay(2000);
-        // we're done - switch the LED back on
-        digitalWrite(ledPin, HIGH);
-    }
-    else
-    {
+
+    } else  {
         // Failed to open connection
-        Serial << F("Failed to open connection to") << serverHost << endl;
-        // force a 2 second delay
-        delay(2000);
-        digitalWrite(ledPin, HIGH);
-    }
+        Serial << F("Failed to open connection to ") << serverHost << endl;
+    }
+
+    // force a 2 second delay
+    delay(2000);
+
+    // we're done - switch the LED back on
+    digitalWrite(ledPin, HIGH);

     WiFly.setDebugChannel( NULL );
     return 0;
 }
+
+/**
+ * Flash the status LED
+ */
+void flashLed(int flashes, int frequency)
+{
+    for(int i=0;i<flashes;i++) {
+        digitalWrite(ledPin, HIGH);
+        delay (frequency/2);
+        digitalWrite(ledPin, LOW);
+        delay (frequency/2);
+    }
+}


Zero indexed relay numbers

Zero indexed relay numbers

--- action.ino
+++ action.ino
@@ -10,13 +10,13 @@

 void perform_action(actionmask_t * actions) {
     if (actions->flags.enable_relay_1)
+        set_relay_state(0, !actions->flags.inverted);
+    if (actions->flags.enable_relay_2)
         set_relay_state(1, !actions->flags.inverted);
-    if (actions->flags.enable_relay_2)
+    if (actions->flags.enable_relay_3)
         set_relay_state(2, !actions->flags.inverted);
-    if (actions->flags.enable_relay_3)
+    if (actions->flags.enable_relay_4)
         set_relay_state(3, !actions->flags.inverted);
-    if (actions->flags.enable_relay_4)
-        set_relay_state(4, !actions->flags.inverted);
     if (actions->flags.blink_backlight)
         backlight_blinking = !actions->flags.inverted;


Refactoring/debug fix

Refactoring/debug fix

--- src/Full_decoder/Full_decoder.ino
+++ src/Full_decoder/Full_decoder.ino
@@ -93,7 +93,7 @@
         break;
     }
     DEBUG("Pin #");
-    DEBUGLN(i);
+    DEBUGLN(slot);
     confpins[slot]->print();
 }
 void setup() {


round temp tp .25

round temp tp .25

--- BrewManiac.ino
+++ BrewManiac.ino
@@ -351,23 +351,6 @@

 #if 0 //opt-code

-#define MAIN_SCREEN 	&mainSetup,&mainEventHandler
-
-#define SETUP_SCREEN 	&menuSetup,&menuEventHandler
-
-#define PID_SETTING_SCREEN 	&settingPidSetup,&settingPidEventHandler
-
-#define UNIT_SETTING_SCREEN 	&settingUnitSetup,&settingUnitEventHandler
-
-#define AUTO_SETTING_SCREEN 	&settingAutoSetup,&settingAutoEventHandler
-
-
-#define MANUAL_MODE_SCREEN 	&manualModeSetup,&manualModeEventHandler
-
-#define AUTO_MODE_SCREEN 	&autoModeSetup,&autoModeEventHandler
-
-
-#else
 #define MAIN_SCREEN 0
 #define SETUP_SCREEN 1
 #define PID_SETTING_SCREEN 2
@@ -417,7 +400,7 @@
 }
 #endif
 };
-#endif
+

 byte _currentEventMask;
 //#define setEventMask(a) _currentEventMask=(a)
@@ -1791,10 +1774,11 @@

 	if(_editingStage <=7) // from MashIn,Phytase,Glucanase,Protease,bAmylase,aAmylase1,aAmylase2,MashOut
 	{
-		if(_editingStageAux==0)
+		if(_editingStageAux==0){
 			value = readSettingWord(PS_StageTemperatureAddr(_editingStage));
-		else
-		{
+			// round to .25
+			value = ToTempInStorage(round025(TempFromStorage(value)));
+		}else{
 			value =readSetting(PS_StageTimeAddr(_editingStage));
 			if (value==0) value=1;
 		}


Respone for command

Respone for command

--- SensorBoard.ino
+++ SensorBoard.ino
@@ -31,40 +31,60 @@
 void loop(void)
 {
   byte command[32] ;
+  byte *ptr;
+  ptr = &command[0];
   if ( radio.available() )
     {

       bool done = false;
       while (!done)
       {
-        done = radio.read( &command, sizeof(byte[32]) );
+        done = radio.read( ptr, sizeof(byte[32]) );

 	// Delay just a little bit to let the other unit
 	// make the transition to receiver
 	delay(20);
       }
-      runCommand(command[1],command[2]);
+      runCommand(ptr);
+      Serial.println(ptr[3]);
+      radio.write(ptr, sizeof(byte[32]));
     }

 }
-bool runCommand(byte command, byte parameter)
+bool runCommand(byte *ptr)
 {
-  Serial.println(command);
-  switch (command)
+  Serial.println(ptr[1]);
+  Serial.println(ptr[2]);
+  Serial.println(ptr[3]);
+  switch (ptr[1])
   {
     case 0:
       break;
     case 1:
-      switchOnLight(parameter);
+      if (ptr[3]== 0x00)
+      {
+        switchOnLight(ptr);
+      }
       break;
     case 2:
-      switchOffLight(parameter);
+      if (ptr[3]== 0x00)
+      {
+        switchOffLight(ptr);
+      }
       break;
   }

 }
+
 byte readTemp(void){}
 byte readHum(void){}
 byte readLight(void){}
-bool switchOnLight(byte number){digitalWrite(led, HIGH);}
-bool switchOffLight(byte number){digitalWrite(led, LOW);}
+bool switchOnLight(byte* ptr)
+{
+  digitalWrite(led, HIGH);
+  ptr[3] = 0xFF;
+}
+bool switchOffLight(byte* ptr){
+  digitalWrite(led, LOW);
+  ptr[3] = 0xFF;
+}


Adjust moisture max reading and remove RTC time reading for initial sample reading

--- ARTF_Sensors/examples/MoistureSensorGSM/MoistureSensorGSM.ino
+++ ARTF_Sensors/examples/MoistureSensorGSM/MoistureSensorGSM.ino
@@ -6,9 +6,11 @@
   Notes:
   - This is an early implementation. Parts of code need to be cleaned up
     to remove duplication. But should work for now.
+  - Use 930 MOISTURE_MAX_READING for 3.3v Arduino. About 610 for 5v Arduino
+  - Had to remove RTC time for sample GSM message. Red light on RocketScream stays on...

   Created 8 7 2014
-  Modified 8 7 2014
+  Modified 11 7 2014
 */

 #include <LowPower.h>
@@ -43,7 +45,7 @@
 // Settings
 // -------------------------------
 #define SENSOR_TYPE                "s"
-#define MOISTURE_MAX_READING       450
+#define MOISTURE_MAX_READING       930
 #define SEND_DATA_AFTER_X_READINGS 3
 #define SLEEP_CYCLES               3600
 #define NUM_MOISTURE_READINGS      10
@@ -84,11 +86,7 @@
   // 0. Send a test text message with with moisture reading and time
   // ---------------------------------------------------------------
   int roundedMoisture = takeMoistureReadings();
-
-  rtc.begin();
-  time_t unixTime = rtc.readDateTime();
-
-  String textMessage = String(SENSOR_TYPE) + " " + String(unixTime) + " " + String(roundedMoisture);
+  String textMessage = String(SENSOR_TYPE) + " " + String(roundedMoisture);

   digitalWrite(MOSFET_GSM_PIN, HIGH);
   delay(1500);
@@ -105,6 +103,7 @@

   digitalWrite(MOSFET_GSM_PIN, LOW);
   delay(2000);
+
 }

@@ -230,7 +229,7 @@
   // --------------------------------------
   digitalWrite(MOSFET_MS_PIN, HIGH);
   // Calibration time
-  delay(1000);
+  delay(2000);

   // 3. Take X moisture readings. (One every 200ms)


Set LED off by default, and fixed the temp compare in the loop

--- photo_temp_sensor/PhotoTempSensor.ino
+++ photo_temp_sensor/PhotoTempSensor.ino
@@ -17,11 +17,14 @@
 double currentTempC = 0;
 int counter = 0;

+int LOOP_DELAY_MS = 2500; // 2.5 sec
+int FORCE_SEND_TEMP_INTERVAL_MS = 120000; // 2 min
+
+int TEMP_LOOP_CNT_THRESHOLD;
+
 void printTemp(float celcius, float fahrenheit)
 {
-  char str[100];
-  sprintf(str, "Temperature: %f C, %f F", celcius, fahrenheit);
-  Serial.println(str);
+  Serial.printlnf("Main> Temperature: %f C, %f F", celcius, fahrenheit);
 }

 void test_server(){
@@ -57,9 +60,22 @@

     Serial.println("Main> Initializing... ");

+    // Calculate the number of times we chack to see if the temp has changed
+    // before we forcefully send the data to the server even if the temp
+    // has not changed.
+    TEMP_LOOP_CNT_THRESHOLD = (FORCE_SEND_TEMP_INTERVAL_MS / LOOP_DELAY_MS);
+
+    Serial.printlnf("Main> Loop delay %f (S), %d (MS).", (LOOP_DELAY_MS / 1000), LOOP_DELAY_MS);
+    Serial.printlnf("Main> Time delay before send %f (S), %d (MS)", (FORCE_SEND_TEMP_INTERVAL_MS / 1000), FORCE_SEND_TEMP_INTERVAL_MS);
+    Serial.printlnf("Main> Check temp counter threshold (MAX counter value): %d", TEMP_LOOP_CNT_THRESHOLD);
+
     led.init();
     led.disable();
     led.setColor(YELLOW);
+
+    RGB.control(true);
+    RGB.brightness(0);
+    RGB.control(false);

     Serial.print("Main> My device id: ");
     Serial.println(myDeviceId);
@@ -93,6 +109,12 @@

 double c2f(double c){
   return c * 1.8 + 32.0;
+}
+
+double abs_d(double x){
+  if (x < 0) return x * -1;
+
+  return x;
 }

 void loop()
@@ -148,10 +170,12 @@
     // If the temp has not changed (+/- .5 degrees) no need to send the data
     // However, if the counter reaches 10, then send the data anyway
     // to notify the server that you are still alive :)
-    if (round(celcius) != round(currentTempC) || counter > 10) {
+    double diff = currentTempC - celcius;
+    if (abs_d(diff) > .5 || counter > TEMP_LOOP_CNT_THRESHOLD) {
       led.setColor(BLUE);
+      Serial.print("Main> Sending current temp data to server.");
+      Serial.printlnf("Previous temp: %f C, Current temp: %f C", currentTempC, celcius);
       currentTempC = celcius;
-      Serial.println("Main> Sending temp data to server.");
       if (! client.SendTemperatureData(celcius, fahrenheit)) {
         Serial.println("Main> Failed to send data to server, will try again next time");
       }
@@ -161,16 +185,17 @@

       // If it has failed 5 times to send the data, then assume the service is
       // down and put the system in an error state
-      if(counter > 15){
+      if(counter > TEMP_LOOP_CNT_THRESHOLD + 5){
         Serial.println("Main> Failed to send data to the server several times.  Putting system in error state.");
         is_server_available = false;
       }
     }
-
-    counter = counter + 1;
+    else{
+      counter = counter + 1;
+    }
   }

   led.setColor(GREEN);
   Serial.flush();
-  delay(2500);
-}
+  delay(LOOP_DELAY_MS);
+}


Fixed upload

Fixed upload

--- files/template_photonik/template_photonik_ethernet/template_photonik_ethernet.ino
+++ files/template_photonik/template_photonik_ethernet/template_photonik_ethernet.ino
@@ -34,9 +34,9 @@
 EthernetClient client;

 String currentSensorId = TEMPERATURESENSOR_ID;
-float temperature;
-float humidity;
-float pressure;
+float temperature, humidity, pressure;
+unsigned long  lux;
+unsigned int analogUv;

 DHT dht(DHTPIN, DHTTYPE);
 Barometer barometer;
@@ -67,7 +67,7 @@
   for (byte thisByte = 0; thisByte < 4; thisByte++) {
     // print the value of each byte of the IP address:
     Serial.print(Ethernet.localIP()[thisByte], DEC);
-    Serial.print(".");
+    Serial.println(".");
   }
   Serial.println("STARTING UP");
   barometer.init();
@@ -121,8 +121,8 @@
         currentSensorId = LUXSENSOR_ID;
         break;
       case 5:
-        analogLight = analogRead(UVPIN);
-        sensorSample = (String)calcUVIndex(analogLight);
+        analogUv = analogRead(UVPIN);
+        sensorSample = (String)calcUVIndex(analogUv);
         currentSensorId = UVSENSOR_ID;
         break;
     }


Nam is a god

Nam is a god

--- 2018-FirefighterL1/Left_Right_Follow.ino
+++ 2018-FirefighterL1/Left_Right_Follow.ino
@@ -1,29 +1,31 @@
 void upperRightRoom()
 {
-  if (frontRightUltrasonic.getDistance() > closeToWall && rightUltrasonic.getDistance() < closeToWall)
-  {
-    moveSlightLeft();
-    delay(500);         // move left diagonal
-    while(rightUltrasonic.getDistance() > closeToWall) {
-      moveSlightRight();
+  if(!dog1){
+    if (frontRightUltrasonic.getDistance() > closeToWall && rightUltrasonic.getDistance() < closeToWall)
+    {
+      moveSlightLeft();
+      delay(500);         // move left diagonal
+      while(rightUltrasonic.getDistance() > closeToWall) {
+        moveSlightRight();
+      }
+      delay(500);    // move diagnol towards the wall until your close to the wall
     }
-    delay(500);    // move diagnol towards the wall until your close to the wall
-  }
-  else if(rightUltrasonic.getDistance() > closeToWall && frontRightUltrasonic.getDistance() > closeToWall)
-  {
-    turn(-90);    // if there is no right wall turn right
-    moveForward(4);
-    turn(30);
-    turn(-210);
-    moveForward(4);
-    turn(-90);
-    rollForward();
-    while(frontRightUltrasonic.getDistance() > closeToWall){
-      delay(50);
+    else if(rightUltrasonic.getDistance() > closeToWall && frontRightUltrasonic.getDistance() > closeToWall)
+    {
+      turn(-90);    // if there is no right wall turn right
+      moveForward(4);
+      turn(30);
+      turn(-210);
+      moveForward(4);
+      turn(-90);
+      rollForward();
+      while(frontRightUltrasonic.getDistance() > closeToWall){
+        delay(50);
+      }
+      turn(-90);
+      stopRobot();
+      delay(500);
     }
-    turn(-90);
-    stopRobot();
-    delay(500);
   }
 }

@@ -34,6 +36,11 @@
   double lateralMove = 5; //how far the robot should move to exit the lower right room

   upperRightRoom();
+  rollForward();
+  while(frontRightUltrasonic.getDistance() > closeToWall){
+    delay(50);
+  }
+

   while(followDirection >= 7)
   {


examples-ltc: crafteffects: remove createThreadFromHeap

This is now built in, so remove the definition here.

Signed-off-by: Sean Cross <d7e19930cc1f42c2d0781f4d9e6f1fe5891bf9cf@xobs.io>

--- examples-ltc/2.Effects/1_Craft_Effects/CraftEffects.ino
+++ examples-ltc/2.Effects/1_Craft_Effects/CraftEffects.ino
@@ -126,18 +126,6 @@
   }
 }

-static thread_t *createThreadFromHeap(size_t size, tprio_t prio,
-                                      tfunc_t pf, void *arg) {
-  thread_t *thr = (thread_t *)malloc(THD_WORKING_AREA_SIZE(size));
-  createThread((void *)thr, THD_WORKING_AREA_SIZE(size), prio, pf, arg);
-
-  /* Mark thr->p_flags as CH_FLAG_MODE_HEAP, so ChibiOS will call free()
-   * on the memory after it exits.
-   */
-  ((uint8_t *)thr)[0x1d] = 1;
-  return thr;
-}
-
 void setup(void) {
   int i;


Watchdog wakeup every 8 seconds

Watchdog wakeup every 8 seconds

--- tracker/tracker.ino
+++ tracker/tracker.ino
@@ -88,6 +88,8 @@
 #define SLEEP_FLAG_DARK 0  // Gone to sleep because it is dark
 #define SLEEP_FLAG_IDLE 1  // Gone to sleep because nothing to do

+#define AWAKE_TX_MAX 3 // How many transmissions before sleeping
+
 // When the last move was attempted.
 unsigned long move_last = 0;
 // The move delay.
@@ -104,6 +106,7 @@
 byte msgId = 0;

 byte sleep_flag;
+byte awake_tx_count = 0;

 Servo servo_horz;

@@ -118,6 +121,11 @@
   // Just wake up
 }

+ISR(WDT_vect)
+{
+  // Wake up by watchdog
+}
+
 void setup()
 {
     watchdog_setup();
@@ -132,6 +140,8 @@

     pinMode(SERVO_PIN_HORZ_POWER, OUTPUT);
     digitalWrite(SERVO_PIN_HORZ_POWER, LOW); // low = 0n (PNP)
+
+    digitalWrite(LED_DEBUG, HIGH);

     //vw_set_ptt_inverted(true); // Required for DR3100
@@ -165,15 +175,7 @@
     // Transmit after interval
     if (now - tx_last >= tx_interval) {
         tx_last = now;
-
-        // if the LED is off turn it on and vice-versa:
-        if (ledState == LOW) {
-          ledState = HIGH;
-        } else {
-          ledState = LOW;
-        }
-        digitalWrite(LED_DEBUG, ledState);
-
+
         // Send a transmission
         char msg[16];
         sprintf(msg, "%d,wd=%u,mv=%lu", msgId, light_level, readVcc());
@@ -181,8 +183,24 @@
         vw_wait_tx(); // Wait until the whole message is gone
         ++msgId;

-        // Watchdog will wake us up in 8 seconds time.
-        //goToSleep(SLEEP_FLAG_IDLE);
+        ++awake_tx_count;
+        if (awake_tx_count > AWAKE_TX_MAX) {
+          awake_tx_count = 0;
+
+          // Turn off the servo
+          servoOff();
+
+          digitalWrite(LED_DEBUG, LOW);
+
+          // Watchdog will wake us up in 8 seconds time.
+          goToSleep(SLEEP_FLAG_IDLE);
+
+          digitalWrite(LED_DEBUG, HIGH);
+
+          // Turn on the servo (todo: leave servo off for much longer)
+          servoOn();
+        }
+
     }
 }

@@ -234,6 +252,22 @@
 }

 /**
+ *  Power up the servo
+ */
+void servoOn()
+{
+  digitalWrite(SERVO_PIN_HORZ_POWER, LOW); // low = 0n (PNP)
+}
+
+/**
+ *  Power down the servo
+ */
+void servoOff()
+{
+  digitalWrite(SERVO_PIN_HORZ_POWER, HIGH); // low = 0n (PNP)
+}
+
+/**
  * Watchdog for while awake to ensure things are ticking over.
  */
 void watchdog_setup()
@@ -243,7 +277,19 @@

   // Reset after 8 seconds,
   // unless wdt_reset(); has been successfully called
-  wdt_enable(WDTO_8S);
+
+  /* In order to change WDE or the prescaler, we need to
+   * set WDCE (This will allow updates for 4 clock cycles).
+   */
+  WDTCSR |= (1<<WDCE) | (1<<WDE);
+
+  /* set new watchdog timeout prescaler value */
+  WDTCSR = 1<<WDP0 | 1<<WDP3; /* 8.0 seconds */
+
+  /* Enable the WD interrupt (note no reset). */
+  WDTCSR |= _BV(WDIE);
+
+  //wdt_enable(WDTO_8S);
   wdt_reset();
 }

@@ -253,6 +299,7 @@

   // Power down the periferals
   digitalWrite(PIN_PERIF_POWER, HIGH);
+

   cli();

@@ -294,6 +341,7 @@

   // Power up the periferals
   digitalWrite(PIN_PERIF_POWER, LOW); // (PNP)
+
 }

 /**


Update Keypad.ino

Update Keypad.ino

--- ComboKeypad/Keypad.ino
+++ ComboKeypad/Keypad.ino
@@ -1,3 +1,6 @@
+//
+//
+//
 //USER VARIABLES, Variables that YOU change for YOUR preferences
 const int buttons[] {7, 6, 5, 4};   //The PIN of all of the buttons


Not able to differenciate betwwen left 90 degree turn and left 90 degree junction same for the right one also

--- zippy_the_road_runner.ino
+++ zippy_the_road_runner.ino
@@ -101,6 +101,7 @@
 		motorRight.write(speed);
 		delay(delayTime);
 		LED_LEFT_OFF;
+		LED_RIGHT_OFF;
 		break;

 	case 'R':
@@ -109,6 +110,7 @@
 		motorLeft.write(speed);
 		motorRight.write(-speed);
 		delay(delayTime);
+		LED_LEFT_OFF;
 		LED_RIGHT_OFF;
 		break;

@@ -394,6 +396,8 @@
 		// L 90 Junction
 		if (foundLeft && !foundRight && foundStraight)
 		{
+			LED_RIGHT_ON;
+			LED_LEFT_ON;
 			path[pathCounter++] = 'C';
 			BLUETOOTH.println(path[pathCounter - 1]);
 			foundLeft = 1;
@@ -402,6 +406,8 @@
 		// R 90 Junction
 		if (!foundLeft && foundRight && !foundStraight)
 		{
+			LED_RIGHT_ON;
+			LED_LEFT_ON;
 			path[pathCounter++] = 'D';
 			BLUETOOTH.println(path[pathCounter - 1]);
 			foundRight = 1;


Removed knob read for better performance

--- Firmware/R2-Quadcopter/R2-Quadcopter.ino
+++ Firmware/R2-Quadcopter/R2-Quadcopter.ino
@@ -13,10 +13,9 @@
 Servo motor_front;
 Servo motor_back;

-
 // PID variables
-bool auto_stabilisation_mode = false; //activer ou pas le mode auto-stabilisé: utiliser le switch de input 5 ou 6
-int dt = 3;//notre dt est de 100 millisecondes
+bool auto_stabilisation_mode = false; //activer ou pas le mode auto-stabilisé
+int dt = 3;
 double pid_roll_speed_in, pid_roll_angle_in,   pid_roll_out,   pid_roll_setpoint,  roll_error,  Integral_roll_error,  Derivative_roll_error,  last_roll_error, AS_roll_error, AS_Integral_roll_error, AS_Derivative_roll_error, AS_last_roll_error = 0;
 double pid_pitch_speed_in, pid_pitch_angle_in,  pid_pitch_out,  pid_pitch_setpoint, pitch_error, Integral_pitch_error, Derivative_pitch_error, last_pitch_error, AS_pitch_error, AS_Integral_pitch_error, AS_Derivative_pitch_error, AS_last_pitch_error = 0;
 double pid_yaw_speed_in,    pid_yaw_out,       pid_yaw_setpoint,   yaw_error,   Integral_yaw_error,   Derivative_yaw_error,   last_yaw_error = 0;
@@ -26,7 +25,7 @@

 //RX
 int throttle = THROTTLE_RMIN;
-volatile int input[6];
+volatile int input[4];
 unsigned long timer[4];
 byte last_channel[4];

@@ -35,7 +34,6 @@
 float pitch_speed, pitch_angle;
 float yaw_speed, yaw_angle;
 Adafruit_BNO055 bno = Adafruit_BNO055();
-

 ////fonctions de lecture du gyro et accel

@@ -47,21 +45,22 @@

 //calculer inclinaison
 void bno_get_values() {
-  imu::Vector<3> gyroscope = bno.getVector(Adafruit_BNO055::VECTOR_GYROSCOPE);
-  roll_speed = gyroscope.x() * 180 / 3.14159265359;
-  pitch_speed = gyroscope.y() * 180 / 3.14159265359;
-  yaw_speed = gyroscope.z() * 180 / 3.14159265359;
-
-  imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);
-  roll_angle = euler.z();
-  pitch_angle = euler.y();
-
-  pid_roll_speed_in = map(roll_speed, -180, 180, ROLL_WMIN, ROLL_WMAX);
-  pid_pitch_speed_in = map(pitch_speed, -180, 180, PITCH_WMIN, PITCH_WMAX);
-  pid_yaw_speed_in = map(yaw_speed, -180, 180, YAW_WMIN, YAW_WMAX);
-
-  pid_roll_angle_in = map(roll_angle, -180, 180, ROLL_WMIN, ROLL_WMAX);
-  pid_pitch_angle_in = map(pitch_angle, -180, 180, PITCH_WMIN, PITCH_WMAX);
+  if (auto_stabilisation_mode = false) {
+    imu::Vector<3> gyroscope = bno.getVector(Adafruit_BNO055::VECTOR_GYROSCOPE);
+    roll_speed = gyroscope.x() * 180 / 3.14159265359;
+    pitch_speed = gyroscope.y() * 180 / 3.14159265359;
+    yaw_speed = gyroscope.z() * 180 / 3.14159265359;
+    pid_roll_speed_in = map(roll_speed, -180, 180, ROLL_WMIN, ROLL_WMAX);
+    pid_pitch_speed_in = map(pitch_speed, -180, 180, PITCH_WMIN, PITCH_WMAX);
+    pid_yaw_speed_in = map(yaw_speed, -180, 180, YAW_WMIN, YAW_WMAX);
+  }
+  else {
+    imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);
+    roll_angle = euler.z();
+    pitch_angle = euler.y();
+    pid_roll_angle_in = map(roll_angle, -180, 180, ROLL_WMIN, ROLL_WMAX);
+    pid_pitch_angle_in = map(pitch_angle, -180, 180, PITCH_WMIN, PITCH_WMAX);
+  }
 }

@@ -69,13 +68,6 @@

 //calculer l'output et l'ecrire
 void control_update() {
-
-  if (input[5] < 1500) {
-    auto_stabilisation_mode = false;
-  }
-  else {
-    auto_stabilisation_mode = true;
-  }
   //fait correspondre les valeurs du joystick aux valeurs des moteurs
   throttle = map(input[2], THROTTLE_RMIN, THROTTLE_RMAX, MOTOR_ZERO_LEVEL, MOTOR_MAX_LEVEL);

@@ -110,21 +102,15 @@
   pinMode(A1, INPUT);
   pinMode(A2, INPUT);
   pinMode(A3, INPUT);
-  pinMode(A4, INPUT);
-  pinMode(A5, INPUT);
 }

 //fonction qui lit les valeurs de la radio
 void rx_read() {
-  //TODO: Try with interrupts
   input[0] = pulseIn(A0, HIGH);
   input[1] = pulseIn(A1, HIGH);
   input[2] = pulseIn(A2, HIGH);
   input[3] = pulseIn(A3, HIGH);
-  input[4] = pulseIn(A4, HIGH); //Knob right
-  input[5] = pulseIn(A5, HIGH); //Knob left
 }
-

 //fonctions de debugging
 void print_rx_values() {
@@ -135,10 +121,6 @@
   Serial.print(input[2]);
   Serial.print(",");
   Serial.print(input[3]);
-  Serial.print(",");
-  Serial.print(input[4]);
-  Serial.print(",");
-  Serial.println(input[5]);
 }
 void print_pitch_and_roll() {
   Serial.print(mR);
@@ -162,15 +144,10 @@
   Serial.print(",");
   Serial.println(mB);
 }
-void print_pid_values() {
-  Serial.print(input[0]);
-  Serial.print(",");
-  Serial.println(pid_roll_out);
-}

 //foncition qui s'execute une fois et au début
 void setup() {
-  Serial.begin(250000);
+  Serial.begin(9600);
   bno_initialisation();
   rx_initialize();
   motor_right.attach(MOTOR_PIN_RIGHT);
@@ -184,5 +161,5 @@
   rx_read();
   bno_get_values();
   control_update();
-  print_motors();
+  print_pitch_and_roll();
 }


test motors with FSR

test motors with FSR

--- pump_Master_test/pump_Master_test.ino
+++ pump_Master_test/pump_Master_test.ino
@@ -1,5 +1,5 @@
 #include <Wire.h>
-//#define FSR_PIN     0
+#define FSR_PIN     0
 #define NUM_MODULES 2
 #define DATA_SIZE   4
 #define ADDR1       0xAA
@@ -9,7 +9,7 @@
 #define P_TIMEOUT  1000
 #define P_START     0
 #define P_STOP      1
-//default masses
+//default masses/times
 // #define BLEED_MASS  5
 // #define TOTAL_TIME  100
 // #define MILK_TIME   30
@@ -25,7 +25,7 @@
 int error();
 // void startTimer();
 // int maxTimer(unsigned long t);
-//int ready = 0;
+// int ready = 0;
 //pump functions
 // int runPump(byte addr, byte pump, float mass);
 // int bleed(byte addr);
@@ -34,10 +34,10 @@
 // int dispenseTea1(byte addr);
 // int dispenseTea2(byte addr);
 //measurements
-// int massFSR();
+int massFSR();
 // int massChange(int initMass);
 // void setTime(int milk, int sugar);
-// int threshold = 0;                      //initial FSR value
+int threshold = 0;                      //initial FSR value
 //float dispenseTime[] = {BLEED_MASS, MILK_TIME, SUGAR_TIME, TEA_TIME};       //mass change setting for pump modes
 byte connect[] = {0,0,0,0};
 byte test[] = {0,1,1,255};
@@ -48,30 +48,31 @@
     if(!initialize()) {
         Serial.println("Initialization Failed");
     }
-    // send(ADDR1, test, 4);
-    // delay(1000);
-    // send(ADDR1, test2, 4);
-    // delay(1000);
+    send(ADDR1, test, 4);
+    delay(1000);
+    send(ADDR1, test2, 4);
+    delay(1000);
     send(ADDR2, test, 4);
     delay(1000);
     send(ADDR2, test2, 4);
     delay(1000);
     test[1] = 0;
     test2[1] = 0;
-    // send(ADDR1, test, 4);
-    // delay(1000);
-    // send(ADDR1, test2, 4);
-    // delay(1000);
+    send(ADDR1, test, 4);
+    delay(1000);
+    send(ADDR1, test2, 4);
+    delay(1000);
     send(ADDR2, test, 4);
     delay(1000);
     send(ADDR2, test2, 4);
     delay(1000);
-    //threshold = massFSR();
+    threshold = massFSR();
 }

 void loop() {
+
     // sendTest(0, massFSR());
-    // Serial.println(massFSR());
+    Serial.println(massFSR());
     // delay(100);
 }

@@ -179,20 +180,20 @@
 // }

-// //get instantaneous FSR mass
-// int massFSR(){
-//     int sensorValue = 0;
-//     int output = 2;
-//     sensorValue = analogRead(FSR_PIN);
-//     //scale from [0,1023] to [0,100]
-//     if(sensorValue>=threshold)
-//         output = (sensorValue-threshold)/10.23;
-//     else
-//         output = 0;
-//     if(output<0 || output>1023)
-//         return error();
-//     return output;
-// }
+//get instantaneous FSR mass
+int massFSR(){
+    int sensorValue = 0;
+    int output = 2;
+    sensorValue = analogRead(FSR_PIN);
+    //scale from [0,1023] to [0,100]
+    if(sensorValue>=threshold)
+        output = (sensorValue-threshold)/10.23;
+    else
+        output = 0;
+    if(output<0 || output>1023)
+        return error();
+    return output;
+}
 // int massChange(int initMass){
 //     return massFSR()-initMass;
 // }


BitBangedSPI::begin(): initialize levels of SCK and MOSI. Correct indentation.

--- build/shared/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino
+++ build/shared/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino
@@ -135,38 +135,37 @@
 };

 class BitBangedSPI {
-  public:
-
-    void beginTransaction(SPISettings settings) {
-	pulseWidth = 1000 / (settings.clock / 1000);
-        if (pulseWidth == 0)
-          pulseWidth = 1;
+public:
+  void begin() {
+    digitalWrite(SCK, LOW);
+    digitalWrite(MOSI, LOW);
+    pinMode(SCK, OUTPUT);
+    pinMode(MOSI, OUTPUT);
+    pinMode(MISO, INPUT);
+  }
+
+  void beginTransaction(SPISettings settings) {
+    pulseWidth = 1000 / (settings.clock / 1000);
+    if (pulseWidth == 0)
+      pulseWidth = 1;
+  }
+
+  void end() {}
+
+  uint8_t transfer (uint8_t b) {
+    for (unsigned int i = 0; i < 8; ++i) {
+      digitalWrite(MOSI, b & 0x80);
+      digitalWrite(SCK, HIGH);
+      delayMicroseconds(pulseWidth);
+      b = (b << 1) | digitalRead(MISO);
+      digitalWrite(SCK, LOW); // slow pulse
+      delayMicroseconds(pulseWidth);
     }
-
-    void begin() {
-
-      pinMode(MISO, INPUT);
-      pinMode(RESET, OUTPUT);
-      pinMode(SCK, OUTPUT);
-      pinMode(MOSI, OUTPUT);
-    }
-
-    void end() {}
-
-    uint8_t transfer (uint8_t b) {
-      for (unsigned int i = 0; i < 8; ++i) {
-        digitalWrite(MOSI, b & 0x80);
-        digitalWrite(SCK, HIGH);
-        delayMicroseconds(pulseWidth);
-        b = (b << 1) | digitalRead(MISO);
-        digitalWrite(SCK, LOW); // slow pulse
-        delayMicroseconds(pulseWidth);
-      }
-      return b;
-    }
-
-  private:
-    unsigned long pulseWidth; // in microseconds
+    return b;
+  }
+
+private:
+  unsigned long pulseWidth; // in microseconds
 };

 static BitBangedSPI SPI;


Fix case in WiFiMulti example

Fix case in WiFiMulti example

--- hardware/esp8266com/esp8266/libraries/ESP8266WiFi/examples/WiFiMulti/WiFiMulti.ino
+++ hardware/esp8266com/esp8266/libraries/ESP8266WiFi/examples/WiFiMulti/WiFiMulti.ino
@@ -6,15 +6,15 @@
 #include <ESP8266WiFi.h>
 #include <ESP8266WiFiMulti.h>

-ESP8266WiFiMulti WiFiMulti = ESP8266WiFiMulti();
+ESP8266WiFiMulti wifiMulti;

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

-    WiFiMulti.addAP("ssid_from_AP_1", "your_password_for_AP_1");
-    WiFiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
-    WiFiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");
+    wifiMulti.addAP("ssid_from_AP_1", "your_password_for_AP_1");
+    wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
+    wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");

 	Serial.println("Connecting Wifi...");
     if(wifiMulti.run() == WL_CONNECTED) {


robot code:	refilled to 80-column max width

--- robot/PiecesOfEight/PiecesOfEight.ino
+++ robot/PiecesOfEight/PiecesOfEight.ino
@@ -62,9 +62,11 @@
   ControlPacket packet;
   Rx64Response rx64;

-  if (xbee.getResponse().isAvailable() && xbee.getResponse().getApiId() == RX_64_RESPONSE)
+  if (xbee.getResponse().isAvailable() &&
+      xbee.getResponse().getApiId() == RX_64_RESPONSE)
     {
-      safetyCounter = 0;	/* reset safety counter (we've got connectivity) */
+      safetyCounter = 0;	/* reset safety counter -- we've got
+				   connectivity. */

       xbee.getResponse().getRx64Response(rx64);
       memcpy(&packet, rx64.getData(), sizeof(ControlPacket));


update

update

--- Garduino.ino
+++ Garduino.ino
@@ -2,7 +2,7 @@
  * Garduino | 0.2
  * Plant Monitoring & Management System on Arduino
  *
- * DHT temp & humidity detecting: Sensor(Digital 2), integers(h,t,hic)
+ * DHT temp & humidity detecting: Sensor(Digital 2), integers(h,t,hic), Wire a 10k Ohm resistor to VCC
  * Servo motor controlling: Motor(Digital 9), integers(motor,pos)
  * IR Controlling (Optional,Not Include): Receiver(Digital 13), integers(RECV_PIN)
  * Water level (Distance) detecting: Sensor(Digital 3 & 2), VCC to Arduino 5v GND to Arduino GND


Fix a printf("%lu") issue

Fix a printf("%lu") issue

Was %lud which resulted in a 'd' after the number

--- arduino/walt/walt.ino
+++ arduino/walt/walt.ino
@@ -123,7 +123,7 @@

 void send(unsigned long l) {
   char s[32];
-  sprintf(s, "%lud", l);
+  sprintf(s, "%lu", l);
   send(s);
 }


Re-add seq bits and make printlns happen sooner

--- SDPArduinoCode/SDPArduinoCode.ino
+++ SDPArduinoCode/SDPArduinoCode.ino
@@ -20,12 +20,15 @@
 // Outbound message definitions
 #define CHECKSUM_FAILED "0CF"
 #define UNRECOGNIZED_COMMAND "0UC"
+#define DONE "0DN"

 // Encoder Board Variables
 #define ROTARY_SLAVE_ADDRESS 5
 #define ROTARY_COUNT 6
 #define PRINT_DELAY 200

+int  lastSeqNo;
+bool done;

 int bytes_to_store = 0;

@@ -47,6 +50,25 @@
    helloWorld();
 }

+
+/////////////////////////////////////////////////////////////////////////////////////
+//                       Check if command not redundant                            //
+/////////////////////////////////////////////////////////////////////////////////////
+bool ignore(int seqNo)
+{
+  if (seqNo == lastSeqNo) {
+    if (done) {
+      Serial.println(DONE);
+    }
+    return true;
+  } else {
+    lastSeqNo = seqNo;
+    done = false;
+    return false;
+  }
+}
+
+
 /////////////////////////////////////////////////////////////////////////////////////
 //                              Helper Functions                                   //
 /////////////////////////////////////////////////////////////////////////////////////
@@ -106,10 +128,10 @@

 void stopRobot(){

-  motorAllStop();
-
   // send reply message
   Serial.println("0RS");
+
+  motorAllStop();
   printMotorPositions();

 }
@@ -119,16 +141,14 @@
 //////////////////////////////////////

 void moveRobotForward(int power){
-
+
+  // need to create a reply message to let the PC acknowledge the accepted request
+  Serial.println("0RF");
+
   //motorStop(0); // this might be useful, in the case the robot is already in a turning move

   motorForward(FRONT_LEFT_MOTOR, power);
   motorForward(FRONT_RIGHT_MOTOR, (int) (power*0.99));
-
-
-  // need to create a reply message to let the PC acknowledge the accepted request and execution
-  Serial.println("0RF");
-
 }

 //////////////////////////////////////
@@ -136,7 +156,10 @@
 //////////////////////////////////////

 void moveRobotBackward(int power){
-
+
+  // send reply message
+  Serial.println("0RB");
+
   //motorStop(0); // again might be useful if the robot is in a turning move

   // stop the motors first incase they are moving forward (to prevent mechinical failure)
@@ -146,9 +169,6 @@
   // set motors to move backwards
   motorBackward(FRONT_LEFT_MOTOR, power);
   motorBackward(FRONT_RIGHT_MOTOR, ((int) power*0.99));
-
-  // send reply message
-  Serial.println("0RB");

 }

@@ -157,31 +177,31 @@
 //////////////////////////////////////

 void rotateRobotLeft(int power){
-
+
+  // send reply message
+  Serial.println("0RL");
+
   // set motors for left rotation
   motorForward(FRONT_RIGHT_MOTOR, power);
   motorBackward(FRONT_LEFT_MOTOR, power);
   motorForward(TURNING_MOTOR, power);

+}
+
+//////////////////////////////////////
+//          Robot Right             //
+//////////////////////////////////////
+
+void rotateRobotRight(int power){
+
   // send reply message
   Serial.println("0RL");

-}
-
-//////////////////////////////////////
-//          Robot Right             //
-//////////////////////////////////////
-
-void rotateRobotRight(int power){
-
   // set motors for left rotation
   motorBackward(FRONT_RIGHT_MOTOR, power);
   motorForward(FRONT_LEFT_MOTOR, power);
   motorBackward(TURNING_MOTOR, power);

-  // send reply message
-  Serial.println("0RL");
-
 }

 //////////////////////////////////////
@@ -189,9 +209,12 @@
 //////////////////////////////////////

 void robotKick(int power){
-
+
+  // send reply message
+  Serial.println("0RK");
+
   int d = 1500 - (power * 10);
-  Serial.println(d);
+  //Serial.println(d);

   motorForward(ACTION_MOTOR, 70);
   delay(200);
@@ -205,28 +228,26 @@
   delay(150);
   motorAllStop();

+}
+
+//////////////////////////////////////
+//          Robot Grab              //
+//////////////////////////////////////
+
+void robotGrab(int power){
+
   // send reply message
-  Serial.println("0RK");
-
-}
-
-//////////////////////////////////////
-//          Robot Grab              //
-//////////////////////////////////////
-
-void robotGrab(int power){
+  Serial.println("0RG");

   // move action motor forward
   motorForward(ACTION_MOTOR,power);
-
-  // send reply message
-  Serial.println("0RG");

 }

 void robotForwardDistance(int distance){

+  Serial.println("0RF");

   // reset dynamicPositions
   resetDynamicPositions();
@@ -250,13 +271,12 @@
     //Serial.println(right);
   }

-  motorAllStop();
-
-  Serial.println("0RF");
+  motorAllStop();
 }

 void robotBackwardDistance(int distance){

+  Serial.println("0RB");

   // reset dynamicPositions
   resetDynamicPositions();
@@ -281,13 +301,13 @@
   }

   motorAllStop();
-
-  Serial.println("0RB");
 }

 void robotLeft(int d){

-    // reset dynamicPositions
+  Serial.println("0RL");
+
+  // reset dynamicPositions
   resetDynamicPositions();

   // setup positions of rotations
@@ -311,9 +331,6 @@
   }

   motorAllStop();
-
-  Serial.println("0RL");
-
 }

 void robotRight(int d){
@@ -463,9 +480,9 @@
     c.trim();

     // if mesage is incomplete send error message and flush serial
-    if(c.length() != 6){
-      Serial.println(c);
+    if(c.length() != 7){
       Serial.println("0IW");
+      //Serial.println(c);
       serialFlush();
       return;
     }
@@ -473,20 +490,23 @@
       // need to check if signuture is our teams first!
       // avoids unessacary computation on the arduino if it is not a message for out team.
       int sig = getSig(c);
-      //int seqNo = getSeqNo(c);
+      int seqNo = getSeqNo(c);

       // Quits if sig belongs to other teams
       // OR if command is redundant (i.e. already executed)
       if(sig != 0){ return; }
+      if(ignore(seqNo)){ return; }

       int opcode = getOpcode(c);
       int arg = getArg(c);
       int check = check_checksum(c, opcode, arg);

+      // flag that shows if command was recognized
+      bool recognized = true;
+
       // if checksum is correct continue decoding message and execute
       if(check == 1){
-

         switch (opcode){

@@ -509,19 +529,20 @@
           case RIGHT:   robotRight(arg);
           break;

-          case KICK: Serial.println("Stage 1"); robotKick(arg); Serial.println("Stage 2");
+          case KICK: robotKick(arg);
           break;

           case GRAB: robotGrab(arg);
           break;

-          case STORE: bytes_to_store = arg; //Serial.println(arg);
-          break;
-
-          default: Serial.println(UNRECOGNIZED_COMMAND);
+          case STORE: bytes_to_store = arg;
+
+          default: Serial.println(UNRECOGNIZED_COMMAND); recognized = false;
           break;

         } // switch
+        if (recognized)
+            done = true;
       } // if checksum
       else{
         // checksum is not correct, sig is therefore message was corrupted


mqtt sketch: delay voor uitlezen temperatuur

--- software/arduino/iota-mqtt/temperature.ino
+++ software/arduino/iota-mqtt/temperature.ino
@@ -15,7 +15,8 @@

 void updateTemperature() {
   sensor.shutdown(false);
-  lastTemperature = sensor.temp();;
+  delay(100);
+  lastTemperature = sensor.temp();

   Serial.print(lastTemperature);
   Serial.println(" C");


report cell info

report cell info

--- sketch_smartlock/sketch_smartlock.ino
+++ sketch_smartlock/sketch_smartlock.ino
@@ -1,9 +1,10 @@
 #include <ArduinoJson.h>
+#include <vmcell.h>
 #include <LGPRS.h>
 #include <LGPRSClient.h>
 #include <LBattery.h>
 #include <LGPS.h>
-#define MQTT_BUFFER_SIZE 256
+#include <LTask.h>
 #include <MQTTClient.h>

 #define JSON_BUF_SIZE 256
@@ -47,7 +48,8 @@
 static LGPRSClient g_net_client;
 static MQTTClient g_mqtt_client;

-static bool g_need_report = true;
+static bool g_report_lock = true;
+static bool g_report_other = true;

 static gpsSentenceInfoStruct g_gps_info;
 static unsigned long g_last_report_ms = 0;
@@ -56,6 +58,43 @@
 static bool g_buzzer_on = false;

 static unsigned long g_check_net_ms = 0;
+
+/*
+  Wrapper to the low-level function vm_cell_open()
+  Initialize the Cell register on LinkIt ONE
+*/
+static boolean cell_open(void *userData) {
+  *(VMINT *)userData = vm_cell_open();
+  return TRUE;
+}
+
+
+/*
+  Wrapper to the low-level function vm_cell_get_cur_cell_info()
+  Get the current cell info. Result is stored into a struct
+*/
+static boolean get_current_cell_info(void *userData) {
+  *(vm_cell_info_struct **)userData = vm_cell_get_cur_cell_info();
+  return TRUE;
+}
+
+/*
+  Wrapper to the low-level function vm_cell_get_nbr_num()
+  Get the number of neighbor cells
+*/
+static boolean get_neighbor_cell_number(void *userData) {
+  *(VMINT **)userData = vm_cell_get_nbr_num();
+  return TRUE;
+}
+
+/*
+  Wrapper to the low-level function vm_cell_get_nbr_cell_info()
+  Get the neighbor cells info. Result is stored into a struct array
+*/
+static boolean get_neighbor_cell_info(void *userData) {
+  *(vm_cell_info_struct***) userData = vm_cell_get_nbr_cell_info();
+  return TRUE;
+}

 static inline void start_motor() {
   digitalWrite(PIN_MOTOR, LOW);
@@ -233,6 +272,14 @@
 }

 static void init_gprs() {
+  Serial.println("vm_cell_open");
+  VMINT rc;
+  do {
+    LTask.remoteCall(&cell_open, (void *)&rc);
+    Serial.println(".");
+    delay(1000);
+  } while (rc != VM_CELL_OPEN_SUCCESS && rc != VM_CELL_OPEN_ALREADY_OPEN);
+
   Serial.println("attaching gprs");
   while (!LGPRS.attachGPRS(g_gprs_apn, g_gprs_username, g_gprs_password)) {
     Serial.println(".");
@@ -276,34 +323,47 @@
 static void check_need_report() {
   if (millis() - g_last_report_ms > 240000) {
     g_last_report_ms = millis();
-    g_need_report = true;
+    g_report_other = true;
   }
 }

 static void handle_report() {
-  if (!g_need_report) {
+  if (!g_report_lock && !g_report_other) {
     return;
   }

   StaticJsonBuffer<JSON_BUF_SIZE> json_buf;
   JsonObject& root = json_buf.createObject();

-  root["lock"] = (g_lock_status == LOCK_LOCKED);
-
-  LGPS.getData(&g_gps_info);
-  String gps = String((char *)g_gps_info.GPGGA);
-  gps.trim();
-  root["gps"] = gps;
-
-  root["battery"] = LBattery.level();
-  root["charge"] = (LBattery.isCharging() == true);
+  if (g_report_lock) {
+    root["lock"] = (g_lock_status == LOCK_LOCKED);
+    g_report_lock = false;
+  }
+
+  if (g_report_other) {
+    LGPS.getData(&g_gps_info);
+    String gps = String((char *)g_gps_info.GPGGA);
+    gps.trim();
+    root["gps"] = gps;
+    root["battery"] = LBattery.level();
+    root["charge"] = (LBattery.isCharging() == true);
+
+    vm_cell_info_struct *current_cell_ptr = NULL;
+    LTask.remoteCall(&get_current_cell_info, (void *)&current_cell_ptr);
+    JsonObject& cell = root.createNestedObject("cell");
+    cell["mcc"] = current_cell_ptr->mcc;
+    cell["mnc"] = current_cell_ptr->mnc;
+    cell["lac"] = current_cell_ptr->lac;
+    cell["ci"] = current_cell_ptr->ci;
+    g_report_other = false;
+  }

   String json;
   root.printTo(json);

   Serial.println("publish: " + json);
   g_mqtt_client.publish(g_report_topic, json);
-  g_need_report = false;
+  g_report_lock = false;
 }

 static void unlock() {
@@ -330,7 +390,8 @@
   if (cmd == "unlock") {
     unlock();
   } else if (cmd == "report") {
-    g_need_report = true;
+    g_report_lock = true;
+    g_report_other = true;
   } else if (cmd == "buzzer") {
     buzzer(1000);
   }
@@ -346,7 +407,7 @@
       } else {
         if (g_lock_unlock_step == 1) {
           stop_motor();
-          g_need_report = true;
+          g_report_lock = true;
           g_lock_status = LOCK_UNLOCKED;
           buzzer(200);
           g_unlocked_ms = millis();
@@ -362,7 +423,7 @@
       } else {
         if (g_lock_unlock_step == 1) {
           stop_motor();
-          g_need_report = true;
+          g_report_lock = true;
           g_lock_status = LOCK_LOCKED;
           buzzer(400);
           Serial.println("locked");
@@ -386,7 +447,7 @@
 }

 static void check_network() {
-  if (millis() - g_check_net_ms > 20000) {
+  if (millis() - g_check_net_ms > 30000) {
     if (!g_mqtt_client.connected()) {
       Serial.println("mqtt connection failed, try reconnect");
       LGPS.powerOff();


Update code for using deep sleep, dht11

Update code for using deep sleep, dht11

--- D1Mini-DHT22-Thingspeak.ino
+++ D1Mini-DHT22-Thingspeak.ino
@@ -1,7 +1,7 @@
 /* Drafted by Jordan Mellish (jordan.mellish@townsville.qld.gov.au)
  * MIT License
- * Description: Basic code for sending DHT22(Temperature and Humidity) data to ThingSpeak with a WeMos D1 Pro or D1 Mini
- *
+ * Description: Basic code for sending DHT11(Temperature and Humidity) data to ThingSpeak with a WeMos D1 Pro or D1 Mini
+ * Including ESP Deep Sleep for 15 minutes.
  */

 /* Import Libraries  */
@@ -10,50 +10,49 @@
 #include <DHT.h>

 /* Definitions */
-#define DHTPIN D4
-#define DHTTYPE DHT22
+#define DHTPIN D3
+#define DHTTYPE DHT11
 DHT dht(DHTPIN, DHTTYPE);
-long lastConnectionTime = 0;
-const int interval = 3600;
+const int sleepTimeS = 900;

 /* Wi-Fi Credentials */
-char ssid[] = "";    //  your network SSID (name)
-char pswd[] = "";   // your network password
+char ssid[] = "YOUR-WIFI-NAME";    //  your network SSID (name)
+char pswd[] = "YOUR-WIFI-PASSWORD";   // your network password
 int status = WL_IDLE_STATUS;
 WiFiClient  client;

 /* ThingSpeak Credentials  */
-unsigned long myChannelNumber = ;
-const char * myWriteAPIKey = "";
+unsigned long myChannelNumber = ; // Enter your channel number from ThingSpeak
+const char * myWriteAPIKey = "YOUR-API-KEY"; //Enter your Write API Key from ThingSpeak

 void setup() {
-  Serial.begin(9600);
+  Serial.begin(115200);
   dht.begin();
   ThingSpeak.begin(client);
-
-}
-
-void loop() {
   if (WiFi.status() != WL_CONNECTED) { connectWiFi();}
-
-  if (millis() - lastConnectionTime > (interval*1000)){
-
+    Serial.print("I'm Awake");
+    delay(2000);
     float h = dht.readHumidity();
     float t = dht.readTemperature();
-
+    Serial.print(t);
+    Serial.print(h);
     if (isnan(h) || isnan(t)) {
       Serial.println("Failed to read from DHT Sensor");
       return;
     } else {
     //ThingSpeak.setField(Field No. , data)
-    ThingSpeak.setField(1, h);
-    ThingSpeak.setField(2, t);
+    ThingSpeak.setField(1, t);
+    ThingSpeak.setField(2, h);

     ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
-    delay(interval * 1000);
+    delay(2000);
+    Serial.println("Back to sleep");
+    ESP.deepSleep(sleepTimeS * 1000000);
     }
-  }
-  delay(5);
+
+}
+
+void loop() {
 }

 void connectWiFi() {
@@ -75,4 +74,3 @@
   Serial.println(WiFi.localIP());
   Serial.println();
 }
-


Reduces thruster power by a factor of 10.

--- src/arbotix_sketch/arbotix_sketch.ino
+++ src/arbotix_sketch/arbotix_sketch.ino
@@ -7,7 +7,7 @@
 const int PACKET_SIZE = 10;
 byte packet[PACKET_SIZE];

-const float POWER_CONVERSION = 90.0/127.0;
+const float POWER_CONVERSION = 9.0/127.0; // 90.0/127.0

 Servo aft_thruster;
 Servo port_thruster;
@@ -15,7 +15,7 @@

 const float ANGLE_CONVERSION = 4096.0/360.0;

-int heartbeat = 1;
+int heartbeat = 0;

 void setup()
 {


Scheduling, feedback, and debug port seem to be working.

I think the firmware is now at the point where I can work on the Android application for a while.

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -53,6 +53,21 @@
   new platypus::AnalogSensor(2),
   new platypus::AnalogSensor(3)
 };
+
+/**
+ * Wrapper for ADK send command that copies data to debug port.
+ * Requires a null-terminated char* pointer.
+ */
+void send(char *str)
+{
+  // Write string to USB.
+  adk.write(strlen(str), (uint8_t*)str);
+  adk.write(3, (uint8_t*)"\r\n");
+
+  // Copy string to debugging console.
+  Serial.print("-> ");
+  Serial.println(str);
+}

 /**
  * Returns a JSON error message to the connected USB device and the
@@ -88,13 +103,7 @@
            "\"args\": \"%s\""
            "}",
            error_message, input_buffer);
-
-  // Report error over USB.
-  adk.write(strlen(output_buffer), (uint8_t*)output_buffer);
-
-  // TODO: if performance issue, remove this line.
-  // Report error to debugging console.
-  Serial.println(output_buffer);
+  send(output_buffer);
 }

 /**
@@ -126,6 +135,14 @@
   // Create a task that decays motor velocity.
   // TODO: move this into Motor class.
   Scheduler.startLoop(motorDecayLoop);
+
+  // Print header indicating that board successfully initialized
+  Serial.println("------------------------------");
+  Serial.println(companyName);
+  Serial.println(url);
+  Serial.println(accessoryName);
+  Serial.println(versionNumber);
+  Serial.println("------------------------------");
 }

 void loop()
@@ -143,7 +160,8 @@
   if (!adk.isReady())
   {
     // Set LED to red when USB is not connected.
-    rgb_led.set(1,0,0);
+    rgb_led.R(1);
+    rgb_led.G(0);

     // Turn off motors.
     for (size_t motor_idx = 0; motor_idx < NUM_MOTORS; ++motor_idx) {
@@ -151,18 +169,24 @@
     }

     // Wait for USB connection again.
+    yield();
     return;
   }

   // Set LED to green when USB is connected.
-  rgb_led.set(0,1,0);
+  rgb_led.R(0);
+  rgb_led.G(1);

   // Read next command from USB.
   adk.read(&bytes_read, INPUT_BUFFER_SIZE, (uint8_t*)input_buffer);
-  if (bytes_read <= 0) return;
-
-  // TODO: remove this debug print
-  Serial.print("RCV: ");
+  if (bytes_read <= 0)
+  {
+    yield();
+    return;
+  }
+
+  // Copy incoming message to debug console.
+  Serial.print("<- ");
   Serial.println(input_buffer);

   // Parse command as JSON string
@@ -269,8 +293,8 @@

   // TODO: move this to another location (e.g. Motor)
   // Send motor status update over USB
-  char motor_update[64];
-  snprintf(motor_update, 64,
+  char motor_update[128];
+  snprintf(motor_update, 128,
     "{"
       "\"m0\":{"
         "\"v\":%f,"
@@ -284,7 +308,7 @@
     motor[0]->velocity(), motor[0]->current(),
     motor[1]->velocity(), motor[1]->current()
   );
-  adk.write(strlen(motor_update), (uint8_t *)motor_update);
-}
-
-
+  send(motor_update);
+}
+
+


The dimmer now publishes a MQTT message with its current status, once it connects to the MQTT broker

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -17,12 +17,13 @@
 unsigned int i = 0;
 unsigned int brightness = 1023;
 bool led_on = false;
+
 // Create an ESP8266 WiFiClient class to connect to the MQTT server.
 WiFiClient client;

 Adafruit_MQTT_Client mqtt(&client, SERVER, SERVERPORT);
 Adafruit_MQTT_Subscribe onoffsw = Adafruit_MQTT_Subscribe(&mqtt, "/light/1");
-Adafruit_MQTT_Publish temp_mqtt = Adafruit_MQTT_Publish(&mqtt, "/temp/1");
+Adafruit_MQTT_Publish status_mqtt = Adafruit_MQTT_Publish(&mqtt, "/light/1/status");

 // Bug workaround for Arduino 1.6.6, it seems to need a function declaration
 // for some reason (only affects ESP8266, likely an arduino-builder bug).
@@ -51,7 +52,9 @@

   // Setup MQTT subscription for onoff feed.
   mqtt.subscribe(&onoffsw);
-
+
+  MQTT_connect();
+  status_mqtt.publish("{\"On\":0, \"Brightness\":100}");
 }


default to DISABLE_OUTPUTS_IDLE uncommented

--- examples/DCCInterface_TurntableControl/DCCInterface_TurntableControl.ino
+++ examples/DCCInterface_TurntableControl/DCCInterface_TurntableControl.ino
@@ -26,7 +26,7 @@

 #ifdef A4988_ENABLE_PIN
 // Uncomment the next line to enable Powering-Off the Stepper when its not running to reduce heating the motor and driver
-//#define DISABLE_OUTPUTS_IDLE
+#define DISABLE_OUTPUTS_IDLE
 #endif

 // By default the stepper motor will move the shortest distance to the desired position.


pin mapping

pin mapping

--- Firmware/JBC-Soldering-Controller/JBC-Soldering-Controller.ino
+++ Firmware/JBC-Soldering-Controller/JBC-Soldering-Controller.ino
@@ -18,14 +18,27 @@

 //Pin Mapping
-const int LPINA = 9;
-const int LPINB = 10;
-const int debug_pin_A = 7;
-const int debug_pin_B = 6;
-const int CS = 7;
-const int ENC_A = 2;  //TODO: determine which interrupt pins to use on the Leonardo
-const int ENC_B = 3;  //TODO: determine which interrupt pins to use on the Leonardo
-const int ENC_BUTTON = 5; //TODO: determine which  pins to use on the Leonardo
+const int ENC_A            = 0;  //TODO: determine which interrupt pins to use on the Leonardo (0, 1, 2, 3, 7 are supported)
+const int ENC_B            = 1;  //TODO: determine which interrupt pins to use on the Leonardo
+const int I2C_SDA          = 2;
+const int I2C_SCL          = 3;
+const int SPARE_4          = 4;
+const int DELL_PSU         = 5;  //TODO: rewire this on the proto board.
+const int debug_pin_B      = 6;
+const int debug_pin_A      = 7;
+const int CS               = 7;
+const int SPARE_8          = 8;
+const int LPINA            = 9;  //Heater PWM
+const int LPINB            = 10;
+const int SPI_MISO         = 14;
+const int SPI_SCLK         = 15;
+const int SPI_MOSI         = 16;
+const int ENC_BUTTON       = 18; //Maybe this should be an interrupt. if it does, we need to move CS to a different pin
+const int SPARE_18         = 18;
+const int SPARE_19         = 19;
+const int CURRENT_FEEDBACK = 20;
+const int CRADLE_SENSOR    = 21;
+

 //Volatile Variables used by the interrupt handlers


Fixed error in Proximity template

Fixed error in Proximity template

--- libraries/BLE/examples/ble_proximity_template/ble_proximity_template.ino
+++ libraries/BLE/examples/ble_proximity_template/ble_proximity_template.ino
@@ -366,7 +366,6 @@
                     Serial.println(F("Already bonded : Advertising started : Waiting to be connected"));
                   }
                 }
-              }
               break;
           }
         }


Check presence of the wifi shield

Check presence of the wifi shield

Signed-off-by: Nicolas Lamirault <57a11b2dec5b8363280015e1663433805cc2169e@gmail.com>

--- arduino/temperature/src/jarvis-dht.ino
+++ arduino/temperature/src/jarvis-dht.ino
@@ -45,6 +45,13 @@
   delay(10);
   Serial.print("[Jarvis-DHT] Connecting to : ");
   Serial.println(WIFI_SSID);
+
+  // check for the presence of the shield:
+  if (WiFi.status() == WL_NO_SHIELD) {
+    Serial.println("[Jarvis-DHT] WiFi shield not present");
+    // don't continue:
+    while(true);
+  }

   WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
   while (WiFi.status() != WL_CONNECTED) {


Document proximity sensor code

Document proximity sensor code

--- arduino/car_system/car_system.ino
+++ arduino/car_system/car_system.ino
@@ -41,6 +41,9 @@

 // This method returns whether the proximity sensor reads within
 // the proximity threshold.
+//
+// Configured for the SRF05 Ultrasonic Sensor:
+// http://www.robot-electronics.co.uk/htm/srf05tech.htm
 bool ProximityActivated() {
   digitalWrite(pinProximityTrigger, LOW);
   delay(2);
@@ -50,9 +53,9 @@

   unsigned long distance = pulseIn(pinProximityEcho, HIGH);
   // Divided by 2 because the sound travels twice the distance
-  // Speed of sound is 343m/sec = 0.0343cm/μs = [1/29.1] cm/μs
-  distance = (distance/2) / 29;
-  //Serial.println(distance);
+  // Divided by 29 because the speed of sound is
+  //   343m/sec = 0.0343cm/μs = [1/29.1] cm/μs
+  distance = distance / 2 / 29;
   return distance < thresholdProximity;
 }


added functionality to receive and handle serial messages

--- arduino/serialTest/serialTest.ino
+++ arduino/serialTest/serialTest.ino
@@ -72,7 +72,6 @@
   float dist;
   //dist = 4 + 5 * 1023.0/(float)val;
   dist = 12343.85 * pow(val, -1.15);
-  Serial.println(dist);
   return dist;
 }


Fix updating the encoder

Fix updating the encoder

--- KomaRoof.ino
+++ KomaRoof.ino
@@ -157,9 +157,9 @@
     previous = grayToBinary[previous & 0x3];
     current = grayToBinary[current & 0x3];

-    if (current > previous)
+    if (current == ((previous+1) & 0x3))
         encoderPosition++;
-    if (current < previous)
+    if (current == ((previous-1) & 0x3))
         encoderPosition--;
 }


implemented windowing, can now layer objects with animation from python

--- Arduino/linkit_duo_led6/linkit_duo_led6.ino
+++ Arduino/linkit_duo_led6/linkit_duo_led6.ino
@@ -1,4 +1,5 @@
-//efade is broken, brightness wrong after demo animation
+// would be nice to shift-in the new pixels from the back buffer
+//efade is broken

 #include <PololuLedStrip.h>
@@ -10,7 +11,7 @@
 #define EASE_COUNT 32
 #define POWER_EASE_COUNT 24
 #define EASE_DELAY 2
-#define POWER_EASE_DELAY 2
+#define POWER_EASE_DELAY 1
 #define EASE_ANIM_MARGIN 15

 #define ANIM_LED_COUNT 64
@@ -159,7 +160,13 @@
   }
 }

-void push_color(rgb_color color, bool display = false, int effect = NO_EFFECT, rgb_color *buffer = colors, int max = ANIM_LED_COUNT){
+// for limiting effects to preserve later pixels
+int window = 0;
+
+void push_color(rgb_color color, bool display = false, int effect = NO_EFFECT, rgb_color *buffer = colors, int max = window){
+  if(max == 0){
+    max = ANIM_LED_COUNT;
+  }
   shift_buffer(buffer, true, max);

   buffer[0] = color;
@@ -586,6 +593,10 @@
   sub_args[0] = atoi(arg);
   arg = strtok(NULL, ",");
   sub_args[1] = atoi(arg);
+}
+
+void set_window(int width){
+  window = width;
 }

 void loop(){
@@ -676,6 +687,7 @@
     else if(is_command(str, "eshift"))   do_elastic_shift(sub_args[0]);
     else if(is_command(str, "pshift"))   do_power_shift(sub_args[0]);
     else if(is_command(str, "pshifto"))  power_shift_object(sub_args[0], sub_args[1]);
+    else if(is_command(str, "window"))   set_window(sub_args[0]);
     else if(is_command(str, "demo"))     do_demo();
     else if(is_command(str, "static"))   start_static();
     else if(is_command(str, "red"))      push_color(red);


defined max speed of motors in a variable

--- arduino/pi_rover/pi_rover.ino
+++ arduino/pi_rover/pi_rover.ino
@@ -17,6 +17,7 @@
 NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

 int motorSpeed = 100;
+int maxMotorSpeed = 250;
 bool isMovingForward = false;
 bool isMovingBackward = false;
 bool safetyDriveMode = true;
@@ -48,13 +49,13 @@
   if (safetyDriveMode) {
     int checkDistanceInterval = map(
       motorSpeed,
-      0, 255,
+      0, maxMotorSpeed,
       500, 0
     );

     int distanceToStop = map(
       motorSpeed,
-      0, 255,
+      0, maxMotorSpeed,
       15, 50
     );

@@ -102,7 +103,7 @@
   motorSpeed = map(
     speedInPercentage,
     0, 100,
-    0, 255
+    0, maxMotorSpeed
   );

   Serial.print(String("Set speed to ") + motorSpeed + " ("+ speedInPercentage +"%)\n");
@@ -178,7 +179,7 @@
 {
   int currentMotorSpeedInPercentage = map(
     motorSpeed,
-    0, 255,
+    0, maxMotorSpeed,
     0, 100
   );


added feature "safety drive mode" which is enabled by default it should prevent driving against something but only when driving forward

--- arduino/pi_rover/pi_rover.ino
+++ arduino/pi_rover/pi_rover.ino
@@ -1,5 +1,9 @@
 #include <AFMotor.h>
 #include <NewPing.h>
+
+#define runEvery(t) for (static typeof(t) _lasttime;\
+                         (typeof(t))((typeof(t))millis() - _lasttime) > (t);\
+                         _lasttime += (t))

 AF_DCMotor motor1(1);
 AF_DCMotor motor2(2);
@@ -15,6 +19,7 @@
 int motorSpeed = 100;
 bool isMovingForward = false;
 bool isMovingBackward = false;
+bool safetyDriveMode = true;

 String input = "";

@@ -38,6 +43,20 @@
     String result = handleCommand(input);
     Serial.print(result + "\n");
     input = "";
+  }
+
+  if (safetyDriveMode) {
+    int checkDistanceInterval = map(
+      motorSpeed,
+      0, 255,
+      500, 0
+    );
+
+    runEvery(checkDistanceInterval) {
+      if (isMovingForward && getDistanceInCm() < 15) {
+          halt(0);
+      }
+    }
   }
 }

@@ -87,7 +106,7 @@
   if(command == "battery") {
     result = checkBatteryStatus(argument);
   } else if(command == "distance") {
-    result = getDistance(argument);
+    result = measureDistance(argument);
   } else if(command == "forward") {
     result = forward(argument);
   } else if(command == "backward") {
@@ -281,7 +300,11 @@
   motor4.setSpeed(motorSpeed);
 }

-String getDistance(int argument) {
+String measureDistance(int argument) {
+  return String("Ping: ") + String(getDistanceInCm()) + String("cm");
+}
+
+int getDistanceInCm() {
   unsigned int uS = sonar.ping();
-  return String("Ping: ") + String(uS / US_ROUNDTRIP_CM) + String("cm");
-}
+  return uS / US_ROUNDTRIP_CM;
+}


new stuff

new stuff

--- m_led/m_led.ino
+++ m_led/m_led.ino
@@ -74,9 +74,19 @@
 	return pptr;
 }

+
 int pframeid=0;
-int initpattern=1;
 int curptr=0;
+void goto_pattern(int pattern_id)
+{
+	curptr=0;
+	pframeid=0;
+	for(int i=0;i<pattern_id;i++)
+	{
+		curptr=increment_pattern(curptr);
+	}
+}
+
 uint8_t curbrightness=255;	//brightness is X=curbrightness/255.  Max brightness is set here
 uint32_t curspeedup=1024; //Slowness factor is X=speedup/1024.  For example, set speedup to 2048 to get a 2x speedup.  set speedup to 512 to get a 50% slowdown.

@@ -86,10 +96,7 @@
 	{
 		strips[i]->setup();
 	}
-	for(int i=0;i<initpattern;i++)
-	{
-		curptr=increment_pattern(curptr);
-	}
+	goto_pattern(1);
 }
 void loop()
 {


Update code to OneButton, and switch to use library-controlled arduino-TCL59116.

--- arduino/rfglow_tcl591xx/rfglow_tcl591xx.ino
+++ arduino/rfglow_tcl591xx/rfglow_tcl591xx.ino
@@ -1,16 +1,14 @@
-#include <avr/pgmspace.h>
+#include <avr/pgmspace.h>
 #include <HardwareSerial.h>

 #include <OneButton.h>

-#include "cc1101.h"
-#include "calibration.h"
-#include "panstamp.h"
+#include <cc1101.h>
+#include <panstamp.h>

 //#define TLC59116_LOWLEVEL 1
 //#define TLC59116_DEV 1
-
-#include "TLC59116.h"
+#include <TLC59116.h>

 // Logging Setup
 #define DEBUG


criado bloco de configurações, sinal configurável, resolves #2

--- EMP-B-Due.ino
+++ EMP-B-Due.ino
@@ -17,37 +17,46 @@

 // Variáveis
+  // Configurações
+    #define ModoBotoes INPUT_PULLUP
+    #define ModoLeds OUTPUT
+    #define SinalAlto LOW
+    #define SinalBaixo HIGH
+    #define SaidaLigada HIGH
+    #define SaidaDesligada LOW
+    #define Verdadeiro true
+    #define Falso false
   // Botões de Entrada Um Clique
     long atraso = 50;
     int estbt_geral;
-    int estbta_geral = HIGH;
+    int estbta_geral = SinalBaixo;
     long atr_geral = 0;
     int estbt_dosador;
-    int estbta_dosador = HIGH;
+    int estbta_dosador = SinalBaixo;
     long atr_dosador = 0;
     int estbt_datador;
-    int estbta_datador = HIGH;
+    int estbta_datador = SinalBaixo;
     long atr_datador = 0;
   // Programa
-    boolean stand_by = false;
-    boolean maquina_ligada = false;
-    boolean dosador_ligado = false;
-    boolean datador_ligado = false;
+    boolean stand_by = Falso;
+    boolean maquina_ligada = Falso;
+    boolean dosador_ligado = Falso;
+    boolean datador_ligado = Falso;

 void setup() {
-  pinMode(bt_geral, INPUT_PULLUP);
-  pinMode(bt_dosador, INPUT_PULLUP);
-  pinMode(bt_datador, INPUT_PULLUP);
+  pinMode(bt_geral, ModoBotoes);
+  pinMode(bt_dosador, ModoBotoes);
+  pinMode(bt_datador, ModoBotoes);

-  pinMode(led_geral, OUTPUT);
-  pinMode(led_dosador, OUTPUT);
-  pinMode(led_datador, OUTPUT);
+  pinMode(led_geral, ModoLeds);
+  pinMode(led_dosador, ModoLeds);
+  pinMode(led_datador, ModoLeds);

   // Define estado inicial das saídas
-  digitalWrite(led_geral, LOW);
-  digitalWrite(led_dosador, LOW);
-  digitalWrite(led_datador, LOW);
+  digitalWrite(led_geral, SaidaDesligada);
+  digitalWrite(led_dosador, SaidaDesligada);
+  digitalWrite(led_datador, SaidaDesligada);
 }

@@ -78,7 +87,7 @@
     }
   } else {
     delay(3000);
-    stand_by = true;
+    stand_by = Verdadeiro;
   }
 }

@@ -95,12 +104,11 @@
   if ((millis() - *atr_ant) > atraso) {
     if (leitura != *estado) {
       *estado = leitura;
-      if (*estado == LOW) {
+      if (*estado == SinalAlto) {
         *funcao = !*funcao;
       }
     }
   }
-  // digitalWrite(saida, *est_saida);
   *est_ant = leitura;
 }

@@ -109,11 +117,11 @@
 }

 void liga(byte saida){
-  digitalWrite(saida, HIGH);
+  digitalWrite(saida, SaidaLigada);
 }

 void desliga(byte saida){
-  digitalWrite(saida, LOW);
+  digitalWrite(saida, SaidaDesligada);
 }