Use NES_BITCOUNT for NES!

Use NES_BITCOUNT for NES!

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -213,7 +213,7 @@
 #ifdef MODE_2WIRE_SNES
     read_shiftRegister< SNES_LATCH , SNES_DATA , true >( NES_BITCOUNT );
 #else
-    read_shiftRegister< SNES_LATCH , SNES_DATA , SNES_CLOCK >( SNES_BITCOUNT );
+    read_shiftRegister< SNES_LATCH , SNES_DATA , SNES_CLOCK >( NES_BITCOUNT );
 #endif
     interrupts();
     sendRawData( 0 , NES_BITCOUNT );


Round voltage/temp to 2 decimal places

Round voltage/temp to 2 decimal places

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -141,7 +141,7 @@
 #ifdef TEMP_MONITORING_ENABLED
 void writeTempMonitorData() {
     Serial.print(F("t "));
-    Serial.print(tempMonitor.value, DEC);
+    Serial.print(tempMonitor.value, 2);
     Serial.println();
 }
 #endif
@@ -149,7 +149,7 @@
 #ifdef VOLTAGE_MONITORING_ENABLED
 void writeVoltMonitorData() {
     Serial.print(F("v "));
-    Serial.print(voltMonitor.value, DEC);
+    Serial.print(voltMonitor.value, 2);
     Serial.println();
 }
 #endif


Fix signed/unsigned problem

Fix signed/unsigned problem

--- geiger_esp/geiger_esp.ino
+++ geiger_esp/geiger_esp.ino
@@ -24,7 +24,7 @@
 static volatile unsigned long counts = 0;

 static int secondcounts[60];
-static int secidx_prev = 0;
+static unsigned long int secidx_prev = 0;
 static unsigned long int count_prev = 0;
 static unsigned long int second_prev = 0;


Began program layout

Began program layout

Better structural description; revised input structure, program
organiaation

--- csarc/csarc.ino
+++ csarc/csarc.ino
@@ -1,5 +1,14 @@
+/* we'd like to be able to do a couple things with newline-terminated commands.
+ *
+ *  set a constant color value: "V#FFFFFF"
+ *  make gradient pulses between two colors: "G#000000:#FFFFFF:pulseTime"
+ *  ???
+ */
+
+
+
 #include "RGBdriver.h"
-#define CLK 2//pins definitions for the driver
+#define CLK 2 //pin definitions for the driver
 #define DIO 3

 RGBdriver Driver(CLK,DIO);
@@ -13,28 +22,46 @@
 }

 void loop() {
-  while (Serial.available() > 0) {
-    // each input is in the form 000,123,255\n
-
-    //parseInt skips the first non-digit and non-minus sign chars, so input is split:
-    red = Serial.parseInt();  // 123
-    green = Serial.parseInt();// (,)123
-    blue = Serial.parseInt(); // (,)123
-    if (Serial.read() == '\n') { //data probably received successfuly
-      red = constrain(red, 0, 255);
-      green = constrain(green, 0, 255);
-      blue = constrain(blue, 0, 255);

-      Driver.begin();
-      Driver.SetColor(red, green, blue);
-      Driver.end();
+  char input[255];

-      // report back hex values
-      Serial.print(red, HEX);
-      Serial.print(green, HEX);
-      Serial.println(blue, HEX);
+  Serial.readStringUntil('\n').toCharArray(input,255);
+  if (input!="") { // if connected
+    switch (input[0]) {
+      case 'V': {
+        // set value specified in rest of V#FFFFFF inpupt
+        break;
+      }
+    case 'G' : {
+        // run gradient pulse between a and b with appropriate timestep; "G#000000:#123456:time" input
+        break;
+      }
+    }
+  }

-
-     }
-  }
+// TODO: reuse relevant driver code (like two lines)
+//  while (Serial.available() > 0) {
+//    // each input is in the form 000,123,255\n
+//
+//    //parseInt skips the first non-digit and non-minus sign chars, so input is split:
+//    red = Serial.parseInt();  // 123
+//    green = Serial.parseInt();// (,)123
+//    blue = Serial.parseInt(); // (,)123
+//    if (Serial.read() == '\n') { //data probably received successfuly
+//      red = constrain(red, 0, 255);
+//      green = constrain(green, 0, 255);
+//      blue = constrain(blue, 0, 255);
+//
+//      Driver.begin();
+//      Driver.SetColor(red, green, blue);
+//      Driver.end();
+//
+//      // report back hex values
+//      Serial.print(red, HEX);
+//      Serial.print(green, HEX);
+//      Serial.println(blue, HEX);
+//
+//
+//     }
+//  }
 }


Add subscriber to 'set_fob_mode' topic to set the fob mode. (#52)

--- Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
+++ Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
@@ -38,6 +38,7 @@
 #include <victoria_nav_msgs/Odom2DRaw.h>
 #include <victoria_sensor_msgs/DistanceDisplacement1D.h>
 #include <victoria_sensor_msgs/EncoderCount.h>
+#include <victoria_sensor_msgs/FobMode.h>
 #include <victoria_sensor_msgs/IMURaw.h>

 // Teensy pin definitions
@@ -124,6 +125,10 @@
 void cmdVelCallback(const geometry_msgs::Twist& twist_msg);
 ros::Subscriber<geometry_msgs::Twist> ros_cmd_vel_sub("cmd_vel", cmdVelCallback);

+// Set fob mode subscriber
+void setFobModeCallback(const victoria_sensor_msgs::FobMode& fob_mode_msg);
+ros::Subscriber<victoria_sensor_msgs::FobMode> ros_set_fob_mode_sub("set_fob_mode", setFobModeCallback);
+
 // Raw 2D Odometry publisher
 victoria_nav_msgs::Odom2DRaw ros_raw_odom_msg;
 ros::Publisher ros_raw_odom_pub("odom_2d_raw", &ros_raw_odom_msg);
@@ -171,6 +176,7 @@

   // Register ros subscribers
   ros_nh.subscribe(ros_cmd_vel_sub);
+  ros_nh.subscribe(ros_set_fob_mode_sub);

   // Initialize and connect to ros
   ros_nh.getHardware()->setBaud(115200);
@@ -353,6 +359,10 @@

   // Calculate and set  refrence wheel angular velocity
   setReferenceVelocity(vl / wheel_radius, vr / wheel_radius);
+}
+
+void setFobModeCallback(const victoria_sensor_msgs::FobMode& fob_mode_msg) {
+  fob_mode = fob_mode_msg.fob_mode;
 }

 void doMotorController(void) {


Adding drop packets counter Adding position and attitude frame Using microseconds

--- Arduino/ArduinoMAVLink/ArduinoMAVLink.ino
+++ Arduino/ArduinoMAVLink/ArduinoMAVLink.ino
@@ -2,6 +2,11 @@

 #include "/home/bat/sketchbook/libraries/mavlink/ardupilotmega/mavlink.h"        // Mavlink interface
 long last_time = 0;
+int packet_drops;
+const int pi = 3.1415;
+
+uint8_t system_id = 100;
+uint8_t component_id = 200;
 void setup() {
   Serial.begin(57600);
   pinMode(13, OUTPUT);
@@ -9,29 +14,51 @@

 void loop() {
 	// Define the system type (see mavlink_types.h for list of possible types)
-
-	// Initialize the required buffers
+
+        // Initialize the required buffers
 	mavlink_message_t msg;
 	uint8_t buf[MAVLINK_MAX_PACKET_LEN];

-        long t = millis();
-        if (fabs(t-last_time) >= 1000 )
+        long t_us = micros();
+        if (fabs(t_us-last_time) >= 100000 )
         {
           digitalWrite(13, HIGH);
     	  // Pack the message
           // static inline uint16_t mavlink_msg_heartbeat_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
           //	uint8_t type, uint8_t autopilot, uint8_t base_mode, uint32_t custom_mode, uint8_t system_status)
-    	  mavlink_msg_heartbeat_pack(100, 200, &msg, MAV_TYPE_KITE, MAV_AUTOPILOT_GENERIC, MAV_MODE_GUIDED_ARMED, 0, MAV_STATE_ACTIVE);
+    	  mavlink_msg_heartbeat_pack(system_id, component_id, &msg, MAV_TYPE_KITE, MAV_AUTOPILOT_GENERIC, MAV_MODE_GUIDED_ARMED, 0, MAV_STATE_ACTIVE);

     	  // Copy the message to send buffer
     	  uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);

     	  // Send the message (.write sends as bytes)
     	  Serial.write(buf, len);
-          //Serial.println("");
-          last_time = t;
+
+          //static inline uint16_t mavlink_msg_attitude_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
+	  //					       uint32_t time_boot_ms, float roll, float pitch, float yaw, float rollspeed, float pitchspeed, float yawspeed)
+          mavlink_msg_attitude_pack(system_id, component_id, &msg, t_us/1000, 20*pi/180.*sin(2*pi/10.*t_us/1000000.), 10*pi/180.*sin(2*pi/10.*t_us/1000000.), 5*pi/180.*sin(2*pi/10.*t_us/1000000.), 0, 0, 0);
+          len = mavlink_msg_to_send_buffer(buf, &msg);
+          Serial.write(buf, len);
+
+          //static inline uint16_t mavlink_msg_local_position_ned_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
+	  //	uint32_t time_boot_ms, float x, float y, float z, float vx, float vy, float vz)
+          mavlink_msg_local_position_ned_pack(system_id, component_id, &msg, t_us/1000, 50, 20, 10, 0, 0, 0);
+          len = mavlink_msg_to_send_buffer(buf, &msg);
+          Serial.write(buf, len);
+
+          //mavlink_msg_global_position_int_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
+	  //   uint32_t time_boot_ms, int32_t lat, int32_t lon, int32_t alt, int32_t relative_alt, int16_t vx, int16_t vy, int16_t vz, uint16_t hdg)
+          //mavlink_msg_global_position_int_pack(system_id, component_id, &msg, t_ms, 47.4195461*pi/180*1e7, -2.468938*pi/180*1e7, 0, 0, 0, 0, 0, 0);
+
+          //mavlink_msg_gps_raw_int_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
+	  //      uint64_t time_usec, uint8_t fix_type, int32_t lat, int32_t lon, int32_t alt, uint16_t eph, uint16_t epv, uint16_t vel, uint16_t cog, uint8_t satellites_visible)
+          mavlink_msg_gps_raw_int_pack(system_id, component_id, &msg, t_us, 4, 47.4195461*1e7 + 20/6300000.*180/pi*sin(2*pi/10.*t_us/1000000.)*1e7, -2.468938*1e7+20/6300000.*180/pi*cos(2*pi/10.*t_us/1000000.)*1e7, 0,  3, 10, 0, 0, 5);
+          len = mavlink_msg_to_send_buffer(buf, &msg);
+          Serial.write(buf, len);
+
+          last_time = t_us;
         }
-        delay(100);
+        delay(10);
         digitalWrite(13, LOW);
 }

@@ -49,7 +76,7 @@
 			// Handle message
  			switch(msg.msgid) {
 			        case MAVLINK_MSG_ID_SET_MODE: {
-			        	// set mode
+			          //set mode = mavlink_msg_set_mode_get_mode(&msg);
 			        }
 			        break;
 			        case MAVLINK_MSG_ID_COMMAND_ACK:
@@ -62,4 +89,5 @@
 		}
 		// And get the next one
 	}
+  packet_drops += status.packet_rx_drop_count;
 }


Display I2c quality stats

Display I2c quality stats

--- OpenROV/OpenROV.ino
+++ OpenROV/OpenROV.ino
@@ -155,6 +155,7 @@
     Serial.print(loops_per_sec);
     Serial.println(';');
     loops_per_sec = 0;
+    Serial.print(F("nackp:")); Serial.print(Wire.nackpercent()); Serial.print(';');
   }
   if (Output100ms.elapsed(100)) {
     OutputNavData();


minor

minor


Add colorloop support

Add colorloop support

--- ESP8266HueEmulator/ESP8266HueEmulator.ino
+++ ESP8266HueEmulator/ESP8266HueEmulator.ino
@@ -40,14 +40,41 @@
 class PixelHandler : public LightHandler {
   private:
     HueLightInfo _info;
+    int16_t colorloopIndex = -1;
   public:
     void handleQuery(int lightNumber, HueLightInfo newInfo) {
       // define the effect to apply, in this case linear blend
       HslColor newColor = HslColor(getHsb(newInfo.hue, newInfo.saturation, newInfo.brightness));
       HslColor originalColor = strip.GetPixelColor(lightNumber);
       _info = newInfo;
+
+      // cancel colorloop if one is running
+      if (colorloopIndex >= 0) {
+        animator.StopAnimation(colorloopIndex);
+        colorloopIndex = -1;
+      }
       if (newInfo.on)
       {
+        if (_info.effect == EFFECT_COLORLOOP) {
+          //color loop at max brightness/saturation on a 60 second cycle
+          const int SIXTY_SECONDS = 60000;
+          animator.StartAnimation(lightNumber, SIXTY_SECONDS, [ = ](const AnimationParam & param) {
+            // save off animation index
+            colorloopIndex = param.index;
+
+            // progress will start at 0.0 and end at 1.0
+            HslColor updatedColor = HslColor(param.progress, 1, 0.5);
+            RgbColor currentColor = updatedColor;
+            strip.SetPixelColor(lightNumber, updatedColor);
+
+            // loop the animation until canceled
+            if (param.state == AnimationState_Completed) {
+              // done, time to restart this position tracking animation/timer
+              animator.RestartAnimation(param.index);
+            }
+          });
+          return;
+        }
         AnimUpdateCallback animUpdate = [ = ](const AnimationParam & param)
         {
           // progress will start at 0.0 and end at 1.0


Limit number of lights presented due to limited JSON buffer

--- ESP8266HueEmulator/ESP8266HueEmulator.ino
+++ ESP8266HueEmulator/ESP8266HueEmulator.ino
@@ -25,7 +25,7 @@
 //const char* password = "********";

 // Settings for the NeoPixels
-#define pixelCount 30 // Strip has 30 NeoPixels
+#define pixelCount 6 // Max number of exposed lights is directly related to aJSON PRINT_BUFFER_LEN, 14 for 4096
 #define pixelPin 2 // Strip is attached to GPIO2 on ESP-01
 #define colorSaturation 254
 RgbColor red = RgbColor(colorSaturation, 0, 0);


Added LogData routine to write information to monitor. Copy this and paste it into spreadsheet to analyze trike motor and steer control.

--- Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
+++ Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
@@ -309,6 +309,9 @@
     unsigned long elapsedTime = endTime - startTime;
     //Serial.print("loop elapsed time = ");
     //Serial.println(elapsedTime);
+
+    LogData(local_results, &Results);  // data for spreadsheet
+
     // Did we spend long enough in the loop that we should immediately
     // start the next pass?
     if (nextTime > endTime) {
@@ -339,6 +342,12 @@
     Serial.print(results[4]); Serial.print("\t");
     Serial.print(results[5]); Serial.print("\t");
     Serial.println(results[6]);
+}
+void LogData(unsigned long commands[7], SerialData *sensors)  // data for spreadsheet
+{
+     Serial.print(sensors->speed_cmPs); Serial.print("\t");
+     Serial.print(sensors->angle_deg); Serial.print("\t");
+     Print7 (true, commands);
 }

 void startCapturingRCState()


Add support for info button presses

Add support for info button presses

--- Event_Printer/Event_Printer.ino
+++ Event_Printer/Event_Printer.ino
@@ -155,6 +155,14 @@
     else if( hnibble8 == 0x0E ) Serial.print("HIGH");
     else Serial.print("ERROR-Other");
     Serial.println("");
+
+    // INFO BUTTON
+    unsigned char hnibble6 = HI_NIBBLE(data[5]);
+    Serial.print("Info Button: ");
+    if( hnibble6 == 0x05 ) Serial.print("SHORT PRESS");
+    else if( hnibble6 == 0x06 ) Serial.print("LONG PRESS");
+    else Serial.print("ERROR-Other");
+    Serial.println("");
 }


set ino to have the current subset of devices

--- Mqtt433Bridge/Mqtt433Bridge.ino
+++ Mqtt433Bridge/Mqtt433Bridge.ino
@@ -6,6 +6,7 @@
 #include <PubSubClient.h>
 #include "WirelessConfig.h"
 #include "RXCore433.h"
+
 #include "MqttDevice2262n.h"
 #include "MeatThermometer1.h"
 #include "BluelineDevice.h"
@@ -13,7 +14,9 @@
 #include "Device1527.h"
 #include "LacrossTX141.h"
 #include "ArduinoLightSensor.h"
-#include "ArduinoDS18B20Sensor.h"
+#include "Device2262.h"
+//#include "ArduinoDS18B20Sensor.h"
+//#include "ArduinoTHSensor2.h"

 #define RX_433_PIN D4

@@ -30,14 +33,20 @@
   Serial.begin(9600);
   Serial.println("Started\n");

-  receiver.registerDevice(new MqttDevice2262n(200, 50, 4, &client, "esp/house/2262/200"));
+  // note you can only use a subset of the devices at the same time.  This
+  // is because the interrupt handlers need to be in ram and only so many of
+  // them can fit at the same time.
+  receiver.registerDevice(new MqttDevice2262n(200, 75, 2, &client, "esp/house/2262/200"));
+  receiver.registerDevice(new MqttDevice2262n(350, 50, 4, &client, "esp/house/2262/200"));
+  receiver.registerDevice(new Device2262(&client, "esp/house/2262"));
   receiver.registerDevice(new MeatThermometer1(&client, "esp/house/meat/temp"));
   receiver.registerDevice(new BluelineDevice(0x1efd, &client, "esp/house/blueline"));
   receiver.registerDevice(new ArduinoTHSensor(&client, "esp/house/arduinoTHSensor"));
   receiver.registerDevice(new Device1527(350, 50, 4, &client, "esp/house/1527/350"));
   receiver.registerDevice(new LacrossTX141(&client, "esp/house/lacrossTX141"));
   receiver.registerDevice(new ArduinoLightSensor(&client, "esp/house/arduinoLightSensor"));
-  receiver.registerDevice(new ArduinoDS18B20Sensor(&client, "esp/house/arduinoDS18B20Sensor"));
+ // receiver.registerDevice(new ArduinoDS18B20Sensor(&client, "esp/house/arduinoDS18B20Sensor"));
+ // receiver.registerDevice(new ArduinoTHSensor2(&client, "esp/house/arduinoTHSensor"));

   // turn of the Access Point as we are not using it
   wifi.mode(WIFI_STA);


Corrected a type conversion bug within the Arduino Sensor

--- code/demonstration/Arduino/Umgebungskachel/UmgebungskachelCommunication.ino
+++ code/demonstration/Arduino/Umgebungskachel/UmgebungskachelCommunication.ino
@@ -9,9 +9,9 @@

         DynamicJsonBuffer jsonBuffer;
         JsonObject& root = jsonBuffer.createObject();
-        JsonObject& ledToggle = root.createNestedObject("LedToggle");
-        JsonObject& alertTemp = root.createNestedObject("AlertThresholdTemperature");
-        JsonObject& alertBright = root.createNestedObject("AlertThresholdBrightness");
+        JsonObject& ledToggle = root.createNestedObject("ledToggle");
+        JsonObject& alertTemp = root.createNestedObject("alertThresholdTemperature");
+        JsonObject& alertBright = root.createNestedObject("alertThresholdBrightness");

         ledToggle["led"] = get_SensorState_led(&sensorState);
         alertTemp["threshold_temperature"] = get_SensorState_thresholdtemperature(&sensorState);
@@ -24,15 +24,6 @@
         char json[len+1];
         root.prettyPrintTo(json, sizeof(json));
         return json;
-        /*String json = "{";
-	json += "\"led\":\"" + (String)get_SensorState_led(&sensorState) + "\",";
-	json += "\"temperature_f\":"+ dtostrf(get_SensorState_temperaturef(&sensorState),0,4) + ",";
-        json += "\"temperature_c\":"+ dtostrf(get_SensorState_temperaturec(&sensorState),0,4) + ",";
-	json += "\"brightness\":" + dtostrf(get_SensorState_brightness(&sensorState),0,4) + ",";
-	json += "\"threshold_brightness\":"+ dtostrf(get_SensorState_thresholdbrightness(&sensorState),0,4) + ",";
-	json += "\"threshold_temperature\":"+ dtostrf(get_SensorState_thresholdtemperature(&sensorState),0,4);
-	json += "}";
-	return json;*/
 }

 void parseDatastructureFromJson(String json) {
@@ -45,21 +36,17 @@
           Serial.println("parseObject() failed");
           return;
         }
+        Serial.println(json);
         if(root.containsKey("led")) {
 		if(((String)root["led"].asString()).equals("ON")) set_SensorState_led(&sensorState,"ON");
 		if(((String)root["led"].asString()).equals("OFF")) set_SensorState_led(&sensorState,"OFF");
+                Serial.println(root["led"].asString());
 	}
-	if (root.containsKey("temperaturec")) {
-		set_SensorState_temperaturec(&sensorState,stringToDouble(root["temperaturec"].asString()));
-	}
-	if (root.containsKey("brightness")) {
-		set_SensorState_brightness(&sensorState,stringToDouble(root["brightness"].asString()));
-	}
 	if (root.containsKey("threshold_brightness")) {
-		set_SensorState_thresholdbrightness(&sensorState,stringToDouble(root["threshold_brightness"].asString()));
+		set_SensorState_thresholdbrightness(&sensorState,(double)root["threshold_brightness"]);
 	}
 	if (root.containsKey("threshold_temperature")) {
-		set_SensorState_thresholdtemperature(&sensorState,stringToDouble(root["threshold_temperature"].asString()));
+		set_SensorState_thresholdtemperature(&sensorState,(double)root["threshold_temperature"]);
 	}
 }


ADC configuration complete (presumably); correctly reading 16 bits of the result instead of only 8 bits

--- ArduinoAudioSpectrumAnalyzer.ino
+++ ArduinoAudioSpectrumAnalyzer.ino
@@ -47,7 +47,10 @@
   setBit(ADCSRA, ADEN); //enable ADC
   setBit(ADCSRA, ADSC); //start ADC measurements

-  analogReference(DEFAULT); // Use default (5v) aref voltage.
+  // See http://www.robotplatform.com/knowledge/ADC/adc_tutorial_3.html
+  // Leaving ADLAR cleared for the default right-justification and MUX3 though MUX0 bits cleared for only A0 input
+  // Setting the standard 5V reference.
+  ADMUX = 1 << REFS0;

   sei();
 }
@@ -67,7 +70,7 @@
   if (samplingWindowFull)
     return;

-  const uint16_t sample = ADCH;
+  const uint16_t sample = ((uint16_t)ADCH << 8) | ADCL;
   samples[currentSampleIndex] = sample;
   ++currentSampleIndex;


if isWaitingReply, skip other XBee msg, if not, don't pass ID ACK

--- glass/glass.ino
+++ glass/glass.ino
@@ -63,6 +63,7 @@
   BT.begin(57600);
   isWaitingReply = false;
   delay(100);
+
   Serial.print("system begins!");
   ir_time = millis();

@@ -171,19 +172,24 @@
     }
   }

-  if (XBee.available()) {
+  if (XBee.available() && false == isWaitingReply) {
     delay(10);
     DEBUG_PRINT("[XBee]: ");
     readStringfromSerial(&XBee, message);
-
-    if(message[6] == 'T' && message[7] == 'A' && message[8] == 'R') {
-      //if ends with TAR => target experiment msg, no need to send to Glass
-    } else if(true == isPacketValid(message)){
-      DEBUG_PRINT("[BT]: send ");
-      DEBUG_PRINTLN(message);
-      BT.println(message);
-
-    }
+    if(true == isPacketValid(message)) {
+      if(message[6] == 'T' && message[7] == 'A' && message[8] == 'R') {
+        //if ends with TAR => target experiment msg, no need to send to Glass
+      } else if(message[2] == 'A' && message[4] == 'I' && message[5] == 'D') {
+        //ID ack that wasn't handled by list, don't send to glass
+        DEBUG_PRINTLN("Intercepted ID Ack");
+      } else {
+        DEBUG_PRINT("[BT]: send ");
+        DEBUG_PRINTLN(message);
+        BT.println(message);
+
+      }
+    }
+
   }
   delay(10);
 }


Pseudo-working serial comms

Pseudo-working serial comms

--- 00_Firmware/Firmware/Firmware.ino
+++ 00_Firmware/Firmware/Firmware.ino
@@ -83,8 +83,9 @@

 #define EEMODEADDR 0			// The address of the mode stored in EEPROM.
 #define EEMODE_CHANGETIME 5000  // The number of ms to hold the switch before the clip mode is changed.
-#define EEMODE_SYNCPULSE 45		// The Clip looks for a sync pulse on one of the LDRs.
+#define EEMODE_SYNCPULSE  45		// The Clip looks for a sync pulse on one of the LDRs.
 #define EEMODE_HEIGHTONLY 37	// The Clip uses both LDRs to estimate height, no colour involved.
+#define EEMODE_SERIAL     89

 #define PULSE_STATE__NOT_CHECKED  -1	// The sync-pulse routine did not bother checking, too soon since previous check.
 #define PULSE_STATE__NO_PULSE      0	// The sync-pulse check returned no pulse.. Probably off a screen.
@@ -257,92 +258,6 @@
 	// Take us out of setup mode.
 	eRGBMode = eLastMode;
 	updateColour();
-}
-
-/**
- * @brief Check the sync pulse and update relevant global variables.
- * This is automatically rate limited to 5ms samples.
- * It will update the iTargetR,G,B, iLDR1Max and iLDR1Min values if valid pulses are detected.
- * @return -1 if check not performed, 1 if we received an active pulse, 0 if we did not.
- */
-WindowVariance * runningVariance = new WindowVariance( 20 );
-int8_t checkPulse() {
-
-  // Only allow this function to be called once every 5ms.
-  static unsigned long tmr1 = 0;
-  if (!cycleCheck(&tmr1, 2U))
-    return PULSE_STATE__NOT_CHECKED;
-
-  int iLDRValue[] = { analogRead( PIN_LDR1 ), analogRead( PIN_LDR2 ) };
-  int iInVal = iLDRValue[0] - iLDRValue[1];
-  runningVariance->push( iInVal );
-
-  //iInVal = constrain( (int)runningVariance->mean(), -512, 512 ) + 512;
-  int variance = runningVariance->variance();
-
-  int state = map( iInVal, 150, 600, 0, 255 );
-
-  //Serial.print( variance, DEC );
-  //Serial.print( "\t" );
-  //Serial.println( iInVal, DEC );
-
-  if( variance > 15 )
-  {
-
-
-    Serial.print( variance );
-    Serial.print( "\t" );
-    iInVal = map( iInVal, 50, 700, 0, 255 );
-    Serial.print( iInVal, DEC );
-
-    if( iInVal < 100 )
-      Serial.println( "    <--- START" );
-    else
-      Serial.println( "" );
-
-    iTargetPos = constrain(iInVal*2, 0, MOTOR_TRAVEL);
-
-    /*Serial.print( packet->seq, DEC );
-    Serial.print( "\t" );
-    Serial.print( packet->r, DEC );
-    Serial.print( "\t" );
-    Serial.print( packet->g, DEC );
-    Serial.print( "\t" );
-    Serial.println( packet->b, DEC );*/
-
-    /*Serial.print( variance, DEC );
-    Serial.print( "\t" );
-    Serial.print( state, BIN );
-    Serial.print( "\t" );
-    Serial.print( state, HEX );
-    Serial.print( "\t" );
-    Serial.print( iInVal, HEX );
-    Serial.print( "\t" );
-    Serial.println( iLDRValue[0], DEC );*/
-  }
-
-  // Debug graph. Used with SerialChart.
-#ifdef SERIAL_SYNC_DEBUG
-  Serial.print(millis()); Serial.print(","); 		// ms
-  Serial.print(iTargetR); Serial.print(","); 		// Red
-  Serial.print(iTargetG); Serial.print(","); 		// Green
-  Serial.print(iTargetB); Serial.print("\n"); 	// Blue
-#endif
-
-#ifdef SERIAL_SYNC_DEBUG2
-  // Print out the verbose serial debug as csv.
-  Serial.print(millis()); Serial.print(","); 		// ms
-  Serial.print(fSlope); Serial.print(","); 		// slope
-  Serial.print(iLDR1Max); Serial.print(","); 		// Estimated maximum (white + backlight).
-  Serial.print(r); Serial.print(","); 			// Red (estimated)
-  Serial.print(g); Serial.print(","); 			// Green (estimated)
-  Serial.print(b); Serial.print(","); 			// Blue (estimated)
-  Serial.print(iLDR1Min); Serial.print(","); 		// Estimated minimum (black + backlight).
-  Serial.println(iLDRValue);						// ldr raw
-#endif
-
-  // Assume we're always active, for now.
-  return PULSE_STATE__ACTIVE_PULSE;
 }

 /**
@@ -440,19 +355,29 @@
 	configure();

 	// Start the serial port.
-	Serial.begin(9600);
+	Serial.begin(115200);

 	// Wait two seconds.
-	Serial.println("hello world");
+	Serial.println("Boot v2.0");

 	// Select a default clip mode from the set of possible modes, if one is not set.
 	eClipMode = EEPROM.read(EEMODEADDR);
-	if (eClipMode != EEMODE_SYNCPULSE && eClipMode != EEMODE_HEIGHTONLY)
-	{
-		EEPROM.write(EEMODEADDR, EEMODE_HEIGHTONLY);
-		eClipMode = EEMODE_HEIGHTONLY;
-	}
-
+        switch( eClipMode )
+        {
+          case EEMODE_SYNCPULSE:
+            break;
+          case EEMODE_HEIGHTONLY:
+            break;
+          case EEMODE_SERIAL:
+            break;
+          default:
+            eClipMode = EEMODE_HEIGHTONLY;
+            EEPROM.write(EEMODEADDR, EEMODE_HEIGHTONLY);
+        }
+
+        // Debug Mode
+        eClipMode = EEMODE_SERIAL;
+
 	// Wait for a random time so that not all clips zero their motor at the same time.
 	randomSeed(analogRead(PIN_RND));
 	uint16_t randomWait = random(1000);
@@ -477,47 +402,181 @@
 	if (!cycleCheck(&tmrModeCheck, 10U))
 		return;

-	// State for button press detection.
-	static long tmrButtonPress = -1;
-	static boolean bLastState  = true;
-	boolean bState = digitalRead(PIN_SWBOT) == LOW;
-
-	// Store the time when we go from a not pressed to a pressed state.
-	if (bState == true && bLastState == false)
-	{
-		tmrButtonPress = millis();
-	}
-	else if (bState == false && bLastState == true)
-	{
-		tmrButtonPress = -1;
-	}
-	bLastState = bState;
-
-	// If SWBOT has been pressed for X seconds, switch mode.
-	if (tmrButtonPress != -1 && (millis() - tmrButtonPress) > EEMODE_CHANGETIME)
-	{
-		// Prevent it from triggering multiple times.
-		tmrButtonPress = -1;
-
-		// Toggle mode.
-		int iMode = EEPROM.read(EEMODEADDR);
-		if (iMode == EEMODE_SYNCPULSE)
-		{
-			//Serial.println("height mode");
-			EEPROM.write(EEMODEADDR, EEMODE_HEIGHTONLY);
-			eRGBMode  = RGBMODE_NONE;
-			eClipMode = EEMODE_HEIGHTONLY;
+        if( digitalRead(PIN_SWBOT) == HIGH )
+          return;
+
+        while( digitalRead(PIN_SWBOT) == LOW )
+        {
+          switch( eClipMode )
+          {
+            case EEMODE_HEIGHTONLY:
+              pRGB.setPixelColor(0,  0, 255, 0);
+
+              eRGBMode  = RGBMODE_SCREEN;
+              eClipMode = EEMODE_SYNCPULSE;
+              break;
+
+            case EEMODE_SYNCPULSE:
+              pRGB.setPixelColor(0,  0, 0, 255);
+
+              eRGBMode  = RGBMODE_NONE;
+              eClipMode = EEMODE_SERIAL;
+              break;
+
+            case EEMODE_SERIAL:
+              pRGB.setPixelColor(0,  255, 0, 0);
+
+              eRGBMode  = RGBMODE_NONE;
+              eClipMode = EEMODE_HEIGHTONLY;
+              break;
+
+            default:
+              pRGB.setPixelColor(0,  255, 0, 0);
+              eRGBMode  = RGBMODE_NONE;
+              eClipMode = EEMODE_HEIGHTONLY;
+          }
+
+          pRGB.show();
+          delay( 1000 );
+        }
+
+        for( int i=0; i<3; i++ )
+        {
+          switch( eClipMode )
+          {
+            case EEMODE_HEIGHTONLY:
+              pRGB.setPixelColor(0,  255, 0, 0);
+              break;
+            case EEMODE_SYNCPULSE:
+              pRGB.setPixelColor(0,  0, 255, 0);
+              break;
+            case EEMODE_SERIAL:
+              pRGB.setPixelColor(0,  0, 0, 255);
+              break;
+          }
+          pRGB.show();
+          delay( 100 );
+          pRGB.setPixelColor(0,  0, 0, 0);
+          pRGB.show();
+          delay( 100 );
+        }
+
+        EEPROM.write( EEMODEADDR, eClipMode );
+}
+
+/**
+ * @brief Check the sync pulse and update relevant global variables.
+ * This is automatically rate limited to 5ms samples.
+ * It will update the iTargetR,G,B, iLDR1Max and iLDR1Min values if valid pulses are detected.
+ * @return -1 if check not performed, 1 if we received an active pulse, 0 if we did not.
+ */
+int8_t checkPulse() {
+
+	// Only allow this function to be called once every 5ms.
+	static unsigned long tmr1 = 0;
+	if (!cycleCheck(&tmr1, 5U))
+		return PULSE_STATE__NOT_CHECKED;
+
+	// Define static variables.
+	static WindowVariance* pEstimatedMin = new WindowVariance(5);	// Running
+	static WindowVariance* pEstimatedMax = new WindowVariance(5);
+	static int r=0; static int g=0; static int b=0;
+	static float x1,x2,y1,y2 = 0;	// Required for slope differentials.
+	static float fSlope = 0.0f;		// Required for slope differentials.
+	static long iLastMinima = 0;	// The time of the last minimal (ms).
+
+	// Read the LDR and reset the serial debug colour values.
+	int iLDRValue = analogRead(PIN_LDR1);
+	r=0; g=0; b=0;
+
+	// Compute the slope (dLDR/dTime) by comparing it to the previous data.
+	long iCurrentTime = millis();
+	x1 = x2; y1 = y2;
+	x2 = (float)iCurrentTime; y2 = (float)iLDRValue;
+	fSlope = (y1-y2) / (x1-x2);
+
+	// If we are hitting a big dip AND it has been over 50ms since the last one.
+	int iDeltaTime = iCurrentTime - iLastMinima;
+	boolean bSlopeDetected = fSlope < -SYNC_SIGNAL_DROP_THRESHOLD;
+	boolean bWithinPulseRange = iDeltaTime > (DATA_WIDTH - DATA_WIDTH_ERR); // &&  delta < (DATA_WIDTH + DATA_WIDTH_ERR + PULSE_WIDTH + PULSE_WIDTH_ERR);
+
+	// TODO: Reject pulses after a recent slope detection.
+	if (bSlopeDetected && bWithinPulseRange)
+	{
+		// Log the start of the second pulse of the data-frame.
+		iLastMinima = iCurrentTime;
+
+		// If another minma happened BEFORE 500ms  (i.e. the amount of time between a high and a red/green)
+		//  then we know that it is likely attached to the wrong pulse.
+	}
+
+	// Determine if this device has a sync pulse.
+	boolean bActive = iDeltaTime < ( DATA_WIDTH + DATA_WIDTH_ERR ) ;
+
+	// If an active sync pulse, sample the data.
+	if (bActive)
+	{
+		// Make it relative to the start of the minima spike.
+		int iRelativeDelta = iCurrentTime - iLastMinima;
+
+		// Sample the min and max.  Min = immediately after the spike, Max = 4th pulse after the spike.
+		if (checkSample(iRelativeDelta, (PULSE_WIDTH * 0) + SAMPLE_OFFSET, SAMPLE_WINDOW)) {		// Min.
+			pEstimatedMin->push(iLDRValue);
+			iLDR1Min = pEstimatedMin->mean();
+			ldr2.updateMin(iLDR1Min);
 		}
-		else
-		{
-			//Serial.println("sync pulse mode");
-			EEPROM.write(EEMODEADDR, EEMODE_SYNCPULSE);
-			eRGBMode  = RGBMODE_SCREEN;
-			eClipMode = EEMODE_SYNCPULSE;
+		if (checkSample(iRelativeDelta, (PULSE_WIDTH * 4) + SAMPLE_OFFSET, SAMPLE_WINDOW)) {		// Max.
+			pEstimatedMax->push(iLDRValue);
+			iLDR1Max = pEstimatedMax->mean();
+			ldr2.updateMax(iLDR1Max);
 		}
-	}
-}
-
+
+		// Sample the RGB pulses. R = 1st pulse after the spike, B = 3rd pulse after the spike.
+		if (checkSample(iRelativeDelta, (PULSE_WIDTH * 1) + SAMPLE_OFFSET, SAMPLE_WINDOW)) {		// Red.
+			r = iLDRValue;
+			iTargetR = constrain(map(iLDRValue, iLDR1Min, iLDR1Max, 0, 255), 0, 255);
+		}
+		if (checkSample(iRelativeDelta, (PULSE_WIDTH * 2) + SAMPLE_OFFSET, SAMPLE_WINDOW)) {		// Green.
+			g = iLDRValue;
+			iTargetG = constrain(map(iLDRValue, iLDR1Min, iLDR1Max, 0, 255), 0, 255);
+		}
+		if (checkSample(iRelativeDelta, (PULSE_WIDTH * 3) + SAMPLE_OFFSET, SAMPLE_WINDOW)) {		// Blue.
+			b = iLDRValue;
+			iTargetB = constrain(map(iLDRValue, iLDR1Min, iLDR1Max, 0, 255), 0, 255);
+		}
+
+		// Ensure we are in a mode that displays a screen colour.
+		//changeMode(SCREEN);
+	}
+	else
+	{
+		// Turn the LED blue (not on screen).
+		//changeMode(NO_SCREEN);
+	}
+
+	// Debug graph. Used with SerialChart.
+	#ifdef SERIAL_SYNC_DEBUG
+	Serial.print(millis()); Serial.print(","); 		// ms
+	Serial.print(iTargetR); Serial.print(","); 		// Red
+	Serial.print(iTargetG); Serial.print(","); 		// Green
+	Serial.print(iTargetB); Serial.print("\n"); 	// Blue
+	#endif
+
+	#ifdef SERIAL_SYNC_DEBUG2
+	// Print out the verbose serial debug as csv.
+	Serial.print(millis()); Serial.print(","); 		// ms
+	Serial.print(fSlope); Serial.print(","); 		// slope
+	Serial.print(iLDR1Max); Serial.print(","); 		// Estimated maximum (white + backlight).
+	Serial.print(r); Serial.print(","); 			// Red (estimated)
+	Serial.print(g); Serial.print(","); 			// Green (estimated)
+	Serial.print(b); Serial.print(","); 			// Blue (estimated)
+	Serial.print(iLDR1Min); Serial.print(","); 		// Estimated minimum (black + backlight).
+	Serial.println(iLDRValue);						// ldr raw
+	#endif
+
+	// Return if we are active or not.
+	return bActive ? PULSE_STATE__ACTIVE_PULSE : PULSE_STATE__NO_PULSE;
+}

 /**
  * @brief Handle the clip behaviour for sync pulse mode.
@@ -675,6 +734,94 @@

 }

+static const unsigned char BitsSetTable256[256] =
+{
+#   define B2(n) n,     n+1,     n+1,     n+2
+#   define B4(n) B2(n), B2(n+1), B2(n+1), B2(n+2)
+#   define B6(n) B4(n), B4(n+1), B4(n+1), B4(n+2)
+    B6(0), B6(1), B6(1), B6(2)
+};
+
+
+
+WindowVariance * runningVariance = new WindowVariance( 20 );
+int oldState = 0;
+uint16_t bSerialBuffer = 0x00;
+int inputIndex = 0;
+int readState = 0;
+void loopSerialMode()
+{
+  // Only allow this function to be called once every 5ms.
+  static unsigned long tmr1 = 0;
+//if (cycleCheck(&tmr1, 1U))
+  {
+    int iLDRValue[] = { analogRead( PIN_LDR1 ), analogRead( PIN_LDR2 ) };
+    int iInVal = iLDRValue[0] - iLDRValue[1];
+    runningVariance->push( iInVal );
+
+    //iInVal = constrain( (int)runningVariance->mean(), -512, 512 ) + 512;
+    int variance = runningVariance->variance();
+
+    int state = constrain( map( iInVal, -450, 500, 0, 4 ), 0, 4 );
+
+    //Serial.print( variance, DEC );
+    //Serial.print( "\t" );
+    //Serial.print( iInVal, DEC );
+    //Serial.print( "\t" );
+    //Serial.println( state, DEC );
+
+
+    if( state != oldState )
+    {
+      switch( state )
+      {
+        case 0:
+          bSerialBuffer = (bSerialBuffer << 1) | 1;
+          break;
+
+        case 1: inputIndex++; break;
+
+        case 3:
+          bSerialBuffer = (bSerialBuffer << 1);
+          break;
+      }
+
+      byte eFrame = (byte)(bSerialBuffer & 0x01);
+      byte parity = (bSerialBuffer >> 1) & 0x01;
+      byte frame  = (byte)((bSerialBuffer >> 2) & 0xFF);
+      byte startBit = (bSerialBuffer >> 10) & 0x01;
+      byte sFrame    = (bSerialBuffer >> 11) & 0x01;
+
+      oldState = state;
+
+      if( sFrame == 0 && eFrame == 0 && startBit == 1 )
+      {
+        if( (BitsSetTable256[frame] % 2 == 0 && parity == 1) || (BitsSetTable256[frame] % 2 != 0 && parity == 0) )
+        {
+          /*Serial.print( "[" );
+          Serial.print( frame, BIN );
+          Serial.print( " " );
+          Serial.print( frame, HEX );
+          Serial.print( "]\t" );
+          Serial.println( bSerialBuffer, BIN );*/
+
+          Serial.println( frame, BIN );
+
+          //iTargetPos = map( frame & 0x7F, 0, 0x7F, 0, MOTOR_TRAVEL );
+          pRGB.setPixelColor(0,  0, 0, frame & 0x7F);
+          pRGB.show();
+
+          bSerialBuffer = 0;
+        }
+      }
+    }
+
+  }
+
+  moveMotor();
+  //updateColour();
+}
+
 /**
  * Logic loop.
  * The function performs the following tasks:
@@ -697,7 +844,11 @@
 		case EEMODE_SYNCPULSE:
 			loopSyncPulseMode();
 			break;
-
+
+		case EEMODE_SERIAL:
+                        loopSerialMode();
+                        break;
+
 		// Unknown mode.. should not get here.
 		default:
 			break;


correct update of state needs small delay to actually make blink work again???

--- ksp-gegi/ksp-gegi.ino
+++ ksp-gegi/ksp-gegi.ino
@@ -60,8 +60,8 @@
       Serial.print(m_id);
       Serial.print('=');
       Serial.println(state);
-    }
-    m_lastPinState = state;
+      m_lastPinState = state;
+    }
   }
 }

@@ -215,14 +215,14 @@
 				c = -1;
 			}
 			if (c>0 && c!='\r' && c!='\n' && i<16) {
-                                i++;
+        i++;
 				lcd.write(c);
-                                //Serial.print(c,HEX);
+        //Serial.print(c,HEX);
 			}
 		}
-                for (;i<16;i++) {
-                  lcd.write(' ');
-                }
+    for (;i<16;i++) {
+      lcd.write(' ');
+    }
 //        Serial.println("endLCD");
 	}
 }
@@ -262,6 +262,6 @@
   updatePins();
   checkSerialInput();
   updateLeds();
-//  delay(200);
-}
-
+  delay(100);
+}
+


fix: Using micros rather than millis for random number generation to try to avoid dupes

--- kiln.ino
+++ kiln.ino
@@ -92,11 +92,10 @@
 	digitalWrite(POWER_PIN, HIGH);

 	WiFi.selectAntenna(ANT_EXTERNAL);
-
 	delay(WAKEUP_DELAY);
 	Serial.println(String::format("Wifi strength: %d", WiFi.RSSI()));

-	randomSeed(millis());
+	randomSeed(micros());
 }

 void sleep(int seconds) {


Show horiz/vert position while running.

Show horiz/vert position while running.

--- gigapanplus.ino
+++ gigapanplus.ino
@@ -53,14 +53,14 @@
     display.setCursor(0,0);
     display.setTextColor(WHITE);
     display.setTextSize(1);
-    Serial.print("Ready\n");
+    Serial.print(F("Ready\n"));
     display.display();
 }

 void loop() {
     display.clearDisplay();
     display.setCursor(0,0);
-    display.print("Start ");
+    display.print(F("Start "));
     display.display();
     pano.setFocalLength(50);
     pano.setFOV(180, 90);
@@ -69,17 +69,18 @@
     do {
         display.clearDisplay();
         display.setCursor(0,0);
-        display.println("running\n");
-        display.print("pos = ");
+        display.println(F("running\n"));
+        display.display();
+        display.print(F("pos = "));
         display.println(pano.position);
-        display.print("horiz = ");
+        display.print(F("horiz = "));
         display.println(pano.horiz_position);
-        display.print("vert = ");
+        display.print(F("vert = "));
         display.println(pano.vert_position);
         display.display();
     } while(pano.next());
     pano.end();
-    display.println("end");
+    display.println(F("end"));
     display.display();
     delay(10000);
 }


Delete genieArduino_TBM_Jan18_2016.ino

Delete genieArduino_TBM_Jan18_2016.ino


added comments and header row output to serial example

--- LSM303/examples/Serial/Serial.ino
+++ LSM303/examples/Serial/Serial.ino
@@ -1,3 +1,31 @@
+/*
+The sensor outputs provided by the library are the raw 16-bit values
+obtained by concatenating the 8-bit high and low accelerometer and
+magnetometer data registers. They can be converted to units of g and
+gauss using the conversion factors specified in the datasheet for your
+particular device and full scale setting (gain).
+
+Example: An LSM303D gives a magnetometer X axis reading of 1982 with
+its default full scale setting of +/- 4 gauss. The M_GN specification
+in the LSM303D datasheet (page 10) states a conversion factor of 0.160
+mgauss/LSB (least significant bit) at this FS setting, so the raw
+reading of -1982 corresponds to 1982 * 0.160 = 317.1 mgauss =
+0.3171 gauss.
+
+In the LSM303DLHC, LSM303DLM, and LSM303DLH, the acceleration data
+registers actually contain a left-aligned 12-bit number, so the lowest
+4 bits are always 0, and the values should be shifted right by 4 bits
+(divided by 16) to be consistent with the conversion factors specified
+in the datasheets.
+
+Example: An LSM303DLH gives an accelerometer Z axis reading of -16144
+with its default full scale setting of +/- 2 g. Dropping the lowest 4
+bits gives a 12-bit raw value of -1009. The LA_So specification in the
+LSM303DLH datasheet (page 11) states a conversion factor of 1 mg/digit
+at this FS setting, so the value of -1009 corresponds to -1009 * 1 =
+1009 mg = 1.009 g.
+*/
+
 #include <Wire.h>
 #include <LSM303.h>

@@ -11,6 +39,10 @@
   Wire.begin();
   compass.init();
   compass.enableDefault();
+
+  while (!Serial);
+  Serial.println("         Accelerometer           Magnetometer");
+  Serial.println("       X       Y       Z       X       Y       Z");
 }

 void loop()


Update _firmware2.ino

Update _firmware2.ino

--- Arduino/_firmware2/_firmware2.ino
+++ Arduino/_firmware2/_firmware2.ino
@@ -107,8 +107,8 @@
 /////////////////////////////////////////////////////////////////////////////////////////////////////////////
 //                                                 4. LOAD WASHER 1 & 2

-int loadWasher1Pin = A4;
-int loadWasher2Pin = A5;
+int loadWasher1Pin = A5;
+int loadWasher2Pin = A6;

 //Insert Calibration Data Here: Level = AX + B format (rounded to the nearest integer N)
 //We assume that the two load washers have the same calibration curve
@@ -133,7 +133,7 @@
 /////////////////////////////////////////////////////////////////////////////////////////////////////////////
 //                                                5. LEVEL SENSOR

-int levelSensorPin = A3;
+int levelSensorPin = A4;

 //Insert Calibration Data Here: Level = AX + B format (rounded to the nearest integer N)
 //X is the water depth in cm


Load,ave start0jgk

Load,ave start0jgk

--- Arduino/BLuB/BLuB.ino
+++ Arduino/BLuB/BLuB.ino
@@ -9,6 +9,9 @@

 #define kBLuBVersion	"v0.03  2013-June-21  yorgle@gmail.com"

+// v0.04  2013-June-21  cmds: files,load,save then removed. oops
+//			ops	G
+//
 // v0.03  2013-June-21  ops:	all but Gosubs
 //			pointer bugfixes
 //
@@ -53,7 +56,11 @@

 bool trace = false;

-
+#define kNGosubs (15)
+char gosubPtr = 0;
+char * gosubStack[ kNGosubs ];
+
+#define kJRGosubStack	(-6)
 #define kJRDBZError	(-5)
 #define kJRSyntaxError	(-4)
 #define kJRStop		(-3)
@@ -164,6 +171,9 @@
 	//                   ------- ------- ------- ------- -------
 	Serial.println( "    help    mem     vars    new     list" );
 	Serial.println( "    run     tron    troff" );
+#ifdef DESKTOP
+	Serial.println( "    files   load    save" );
+#endif
 	Serial.println( "    elist   eload   esave   enew" );
 	//                   ------- ------- ------- ------- -------
 }
@@ -260,6 +270,64 @@
 	Serial.println( " bytes saved to EEPROM." );
 }

+
+////////////////////////////////////////////////////////////////////////////////
+#ifdef DESKTOP_NEVER
+// a few commands for desktop use.
+
+#include <dirent.h>
+
+#define kProgramFolder	"programs"
+
+void cmd_files( void )
+{
+	DIR * drp = NULL;
+	struct dirent * dent = NULL;
+	int count = 0;
+
+	drp = opendir( kProgramFolder );
+	if( !drp ) {
+		Serial.print( kProgramFolder );
+		Serial.println( ": Unable to read folder." );
+		return;
+	}
+
+	Serial.println( "" );
+
+	while( ((dent = readdir( drp )) != NULL ) )
+	{
+		if( dent->d_type != DT_DIR ) {
+			Serial.print( "    " );
+			Serial.println( dent->d_name );
+			count++;
+		}
+	}
+	closedir( drp );
+
+	if( count != 0 ) Serial.println( "" );
+
+	Serial.print( (long) count, DEC );
+	if( count == 1 )
+		Serial.println( " files found." );
+	else
+		Serial.println( " file found." );
+}
+
+void cmd_load( void )
+{
+	char fname[ 64 ]
+}
+
+void cmd_save( void )
+{
+}
+
+
+
+
+
+#endif
+////////////////////////////////////////////////////////////////////////////////
 #define VarCharToIndex( A )\
 		( (A) - 'a' )

@@ -610,6 +678,15 @@
 	if( OpcodeIs( 'G', 'S' )) {
 		return next;
 	}
+
+#ifdef DOGOSUB
+/*
+#define kNGosubs (15)
+char gosubPtr = 0;
+char * gosubStack[ kNGosubs ];
+if( next == kJRGosubStack ) {
+*/
+
 	if( OpcodeIs( 'G', 'L' )) {
 		return next;
 	}
@@ -620,8 +697,14 @@
 		return next;
 	}
 	if( OpcodeIs( 'R', 'T' )) {
-		return next;
-	}
+		if( gosubPtr <= 0 ) {
+			return kJRGosubStack;
+		} else {
+		gosubPtr--;
+
+		return next;
+	}
+#endif

 	// Digital IO  analog/digital write/read
 	if( OpcodeIs( 'A', 'W' )) { // AnalogWrite PORT VALUE
@@ -659,6 +742,7 @@
 	int next = kJRFirstLine;
 	char *bufc = programRam;

+	gosubPtr = 0;
 	if( *bufc == '\0' ) return;

 	while( *bufc && next != kJRStop ) {
@@ -715,6 +799,10 @@
 		// do the thing!
 		cline = myAtoi( bufc );
 		next = evaluate_line( ln );
+		if( next == kJRGosubStack ) {
+			Serial.println( "Gosub stack error." );
+			next = kJRStop;
+		}
 		if( next == kJRDBZError ) {
 			Serial.println( "Divide By Zero Error." );
 			next = kJRStop;
@@ -878,6 +966,12 @@
 	else if( !strcmp( linebuf, "list" )) { cmd_list(); }
 	else if( !strcmp( linebuf, "vars" )) { cmd_vars(); }
 	else if( !strcmp( linebuf, "help" )) { cmd_help(); }
+
+#ifdef DESKTOP_NEVER
+	else if( !strcmp( linebuf, "files" )) { cmd_files(); }
+	else if( !strcmp( linebuf, "load" )) { cmd_load(); }
+	else if( !strcmp( linebuf, "save" )) { cmd_save(); }
+#endif

 	else if( !strcmp( linebuf, "enew" )) { cmd_enew(); }
 	else if( !strcmp( linebuf, "elist" )) { cmd_elist(); }


Fixed Node Parsing

Fixed Node Parsing

--- Arduino/Node/Node.ino
+++ Arduino/Node/Node.ino
@@ -6,7 +6,7 @@
 #include "XBeeCommunication.h"

 #define MAX_SENSORS 32
-String baseId = "ZZZZZ";
+String baseId = "00000";
 //String nodeId = "test1";

 SoftwareSerial xbee(5, 6); // RX, TX
@@ -47,8 +47,16 @@
 		if(sendOk){
 			response = xcomm.getMessage();
 			xcomm.sendMessage(baseId, "OK");
-			response.trim();
-			numSensors = response.toInt();
+
+			uint8_t start = 0;
+			uint8_t end = response.indexOf(',');
+
+			start = end + 1;
+			end = response.indexOf(',', start);
+			String numberResponse = response.substring(start, end);
+
+			numberResponse.trim();
+			numSensors = numberResponse.toInt();
 			DEBUG_PRINTLN(numSensors);
 		}
     }


serial fixing

serial fixing

--- Koin/fmw_bandung/fmw_bandung.ino
+++ Koin/fmw_bandung/fmw_bandung.ino
@@ -1,6 +1,6 @@
 #include "Hx711.h"
-#include "OutputManager.h"
-#include "Stack.h"
+//~ #include "OutputManager.h"
+//~ #include "Stack.h"
 #define k1 41
 #define k2 52
 #define k3 105
@@ -12,24 +12,23 @@
 static float selisih = 0;

 Hx711 scale(A0,A1);//-- param: A0-data 	A1-sck
-Outputs output;
+//~ Outputs output;
 String inputString = "";
 boolean stringComplete = false;

 void setup()
 {
-    Serial.begin(9600);
-    output.add(13);
-    output.add(RELAYPIN);
-    for (uint8_t i=0;i<=20;i++)
-	{
-		output.add(i);
-	}
-    delay(1000);
-    while(1)
-    {
-
-	}
+    //~ Serial.begin(9600);
+    //~ delay(2000);
+    //~ Serial.println("1");
+    //~ delay(2000);
+    //~ Serial.println("2");
+    //~ delay(2000);
+    //~ Serial.println("3");
+    //~ delay(2000);
+    while (1);
+    //~ output.add(13);
+    //~ output.add(RELAYPIN);
 }

 void loop()
@@ -51,15 +50,17 @@
         if (selisih<TOLERANSI && selisih>-TOLERANSI)
         {
           Serial.println(" Succeed");
-          //~ Relay::on();
+          //~ output.setAll();
           delay(500);
         }
-        else
-        {
-            //~ Relay::off();
-        }
+        //~ else
+        //~ {
+            //~ output.clearAll();
+        //~ }
     }
-    else
-        //~ Relay::off();
+    //~ else
+    //~ {
+        //~ output.clearAll();
+	//~ }
     delay(200);
 }


Smaller

Smaller

remove code for saturation and brightness calculations

--- lampka.ino
+++ lampka.ino
@@ -373,58 +373,10 @@
 #endif
 }

-static inline void nscale8_video_LEAVING_R1_DIRTY( unsigned char & i, unsigned char scale)
-{
-#if SCALE8_C == 1 || defined(LIB8_ATTINY)
-    i = (((int)i * (int)scale) >> 8) + ((i&&scale)?1:0);
-#elif SCALE8_AVRASM == 1
-    asm volatile(
-        "  tst %[i]\n\t"
-        "  breq L_%=\n\t"
-        "  mul %[i], %[scale]\n\t"
-        "  mov %[i], r1\n\t"
-        "  breq L_%=\n\t"
-        "  subi %[i], 0xFF\n\t"
-        "L_%=: \n\t"
-        : [i] "+a" (i)
-        : [scale] "a" (scale)
-        : "r0", "r1");
-#else
-#error "No implementation for scale8_video_LEAVING_R1_DIRTY available."
-#endif
-}
-
-static inline void cleanup_R1()
-{
-#if CLEANUP_R1_AVRASM == 1
-    // Restore r1 to "0"; it's expected to always be that
-    asm volatile( "clr __zero_reg__  \n\t" : : : "r1" );
-#endif
-}
-
-static inline void nscale8x3_video( unsigned char& r, unsigned char& g, unsigned char& b, unsigned char scale)
-{
-#if SCALE8_C == 1
-    unsigned char nonzeroscale = (scale != 0) ? 1 : 0;
-    r = (r == 0) ? 0 : (((int)r * (int)(scale) ) >> 8) + nonzeroscale;
-    g = (g == 0) ? 0 : (((int)g * (int)(scale) ) >> 8) + nonzeroscale;
-    b = (b == 0) ? 0 : (((int)b * (int)(scale) ) >> 8) + nonzeroscale;
-#elif SCALE8_AVRASM == 1
-    nscale8_video_LEAVING_R1_DIRTY( r, scale);
-    nscale8_video_LEAVING_R1_DIRTY( g, scale);
-    nscale8_video_LEAVING_R1_DIRTY( b, scale);
-    cleanup_R1();
-#else
-#error "No implementation for nscale8x3 available."
-#endif
-}
-
 static inline unsigned char scale8_video_LEAVING_R1_DIRTY( unsigned char i, unsigned char scale)
 {
 #if SCALE8_C == 1 || defined(LIB8_ATTINY)
     unsigned char j = (((int)i * (int)scale) >> 8) + ((i&&scale)?1:0);
-    // unsigned char nonzeroscale = (scale != 0) ? 1 : 0;
-    // unsigned char j = (i == 0) ? 0 : (((int)i * (int)(scale) ) >> 8) + nonzeroscale;
     return j;
 #elif SCALE8_AVRASM == 1
     unsigned char j=0;
@@ -441,28 +393,12 @@
         : "r0", "r1");

     return j;
-    // unsigned char nonzeroscale = (scale != 0) ? 1 : 0;
-    // asm volatile(
-    //      "      tst %0           \n"
-    //      "      breq L_%=        \n"
-    //      "      mul %0, %1       \n"
-    //      "      mov %0, r1       \n"
-    //      "      add %0, %2       \n"
-    //      "      clr __zero_reg__ \n"
-    //      "L_%=:                  \n"
-
-    //      : "+a" (i)
-    //      : "a" (scale), "a" (nonzeroscale)
-    //      : "r0", "r1");
-
-    // // Return the result
-    // return i;
 #else
 #error "No implementation for scale8_video_LEAVING_R1_DIRTY available."
 #endif
 }

-void hsv2rgb_rainbow( unsigned char hue, unsigned char sat, unsigned char val, unsigned char colors[3])
+void hsv2rgb_rainbow(unsigned char hue, unsigned char colors[3])
 {
     // Yellow has a higher inherent brightness than
     // any other color; 'pure' yellow is perceived to
@@ -582,30 +518,6 @@
     // although the client can scale green down as well.
     if( G2 ) colors[1] = colors[1] >> 1;
     if( Gscale ) colors[1] = scale8_video_LEAVING_R1_DIRTY( colors[1], Gscale);
-
-    /* commenting out saturation and brightness, keep them at max
-    // Scale down colors if we're desaturated at all
-    // and add the brightness_floor to r, g, and b.
-    if( sat != 255 ) {
-
-        nscale8x3_video( colors[0], colors[1], colors[2], sat);
-
-        unsigned char desat = 255 - sat;
-        desat = scale8( desat, desat);
-
-        //unsigned char brightness_floor = desat;
-        colors[0] += desat;
-        colors[1] += desat;
-        colors[2] += desat;
-    }
-
-    // Now scale everything down if we're at value < 255.
-    if( val != 255 ) {
-
-        val = scale8_video_LEAVING_R1_DIRTY( val, val);
-        nscale8x3_video( colors[0], colors[1], colors[2], val);
-    }
-    */
 }

 ////////////////////////////////////////////////////////////////////////////////////
@@ -662,7 +574,7 @@
   for (unsigned char hue=0; hue < 255; hue++) {
     for (unsigned char index=0; index < PIXELS; index++) {
         unsigned char offset = index * delta * direction;
-        hsv2rgb_rainbow(hue + offset, 255, 255, led_colors[index]);
+        hsv2rgb_rainbow(hue + offset, led_colors[index]);
         }
     show_all_led_colors();
     delay(20);


블링커 모듈 수정

블링커 모듈 수정

아날로그 입력(A3) 추가, MCP4261의 제어 코드 추가, 변수명 정리

--- BlinkerModule/BlinkerModule.ino
+++ BlinkerModule/BlinkerModule.ino
@@ -1,71 +1,90 @@
 #include "OneEuroFilter.h"

-const int volum1Pin = A0;
-const int volum2Pin = A1;
-const int clockPin  = 8;
-const int latchPin  = 9;
-const int dataPin   = 10; // DIGITAL(PWM~)
-const int led1Pin   = 11;
-const int led2Pin   = 12;
+#define VOLUME_L    A0
+#define VOLUME_R    A1
+#define VOLUME_C    A2

-const boolean isMicrosecond = true;
-const boolean isDebugging = true;
-const boolean isFiltering = false;
-double minCutoff = 1.0;
-double beta = 0.007;
-double inputFrequency = 50;
+#define REG_DATA    10 // DIGITAL(PWM~)
+#define REG_LATCH   9
+#define REG_CLOCK   8
+#define POT_SELECT  7
+#define POT_CLOCK   6
+#define POT_MOSI    5
+#define LED_L       4
+#define LED_R       3

-const long milliseconds = 1000;
-const long microseconds = 1000000;
-unsigned long updatePrevious;
+#define MILLISECONDS  1000L
+#define MICROSECONDS  1000000L
+
+const bool isMicrosecond    = true;
+const bool isDebugging      = true;
+const bool isFiltering      = false;
+const float ledDutyCycle    = 0.5;
+const double minCutoff      = 1.0;
+const double beta           = 0.007;
+const double inputFrequency = 50;
+
+unsigned long long updatePrevious;
 OneEuroFilter channel1(inputFrequency, minCutoff, beta);
 OneEuroFilter channel2(inputFrequency, minCutoff, beta);

-int level1;
-int level2;
-int number[4];
-unsigned long level1Previous;
-unsigned long level2Previous;
-boolean led1State;
-boolean led2State;
-const double ledDutyCycle = 0.5;
-unsigned long segmentIndex;
+short level1;
+short level2;
+short level3;
+short number[4];
+unsigned long long level1Previous;
+unsigned long long level2Previous;
+unsigned long long level3Previous;
+bool isLed1On;
+bool isLed2On;
+bool isUpdated;
+unsigned long long segmentIndex;

 void setup() {
   Serial.begin(115200);
-  pinMode(dataPin, OUTPUT);
-  pinMode(latchPin, OUTPUT);
-  pinMode(clockPin, OUTPUT);
-  pinMode(led1Pin, OUTPUT);
-  pinMode(led2Pin, OUTPUT);
-
+  pinMode(REG_DATA, OUTPUT);
+  pinMode(REG_LATCH, OUTPUT);
+  pinMode(REG_CLOCK, OUTPUT);
+  pinMode(POT_MOSI, OUTPUT);
+  pinMode(POT_SELECT, OUTPUT);
+  pinMode(POT_CLOCK, OUTPUT);
+  pinMode(LED_L, OUTPUT);
+  pinMode(LED_R, OUTPUT);
+
   updatePrevious = 0;
   level1Previous = 0;
   level2Previous = 0;
-  led1State = LOW;
-  led2State = LOW;
+  level3Previous = 0;
+  isLed1On = false;
+  isLed2On = false;
+  isUpdated = false;
   segmentIndex = 0;

   registerBlink(2, 500);
 }

 void loop() {
-  unsigned long current = isMicrosecond ? micros() : millis();
-  if (current - updatePrevious >= (isMicrosecond ? microseconds : milliseconds) / inputFrequency) {
+  unsigned long long current = isMicrosecond ? micros() : millis();
+  if (current - updatePrevious >= (isMicrosecond ? MICROSECONDS : MILLISECONDS) / inputFrequency) {
     updatePrevious = current;
-    int received1 = analogRead(volum1Pin);
-    int received2 = analogRead(volum2Pin);
-    int filtered1;
-    int filtered2;
+    short received1 = analogRead(VOLUME_L);
+    short received2 = analogRead(VOLUME_R);
+    short received3 = analogRead(VOLUME_C);
+    short filtered1;
+    short filtered2;
+
+    isUpdated = true;

     if (isFiltering) {
       filtered1 = round(channel1.filter(received1));
       filtered2 = round(channel2.filter(received2));
       level1 = round(filtered1 * (30.0 / 1024.0));
       level2 = round(filtered2 * (30.0 / 1024.0));
+      level3 = round(received3 * (256.0 / 1024.0));
     } else {
       level1 = round(received1 * (30.0 / 1024.0));
       level2 = round(received2 * (30.0 / 1024.0));
+      level3 = round(received3 * (256.0 / 1024.0));
     }

     if (isDebugging) {
@@ -89,64 +108,75 @@

   current = isMicrosecond ? micros() : millis();
   if (level1 == 0) {
-    led1State = LOW;
-    digitalWrite(led1Pin, led1State);
+    isLed1On = false;
+    digitalWrite(LED_L, LOW);
   } else {
-    if (current - level1Previous >= (isMicrosecond ? microseconds : milliseconds) / level1) {
+    if (current - level1Previous >= (isMicrosecond ? MICROSECONDS : MILLISECONDS) / level1) {
       level1Previous = current;
-      led1State = HIGH;
-      digitalWrite(led1Pin, led1State);
+      isLed1On = true;
+      digitalWrite(LED_L, HIGH);
     } else {
-      if (current - level1Previous >= (isMicrosecond ? microseconds : milliseconds) / level1 * ledDutyCycle) {
-        if (led1State == HIGH) {
-          led1State = LOW;
-          digitalWrite(led1Pin, led1State);
+      if (current - level1Previous >= (isMicrosecond ? MICROSECONDS : MILLISECONDS) / level1 * ledDutyCycle) {
+        if (isLed1On == true) {
+          isLed1On = false;
+          digitalWrite(LED_L, LOW);
         }
       }
     }
   }
   if (level2 == 0) {
-    led2State = LOW;
-    digitalWrite(led2Pin, led2State);
+    isLed2On = false;
+    digitalWrite(LED_R, isLed2On);
   } else {
-    if (current - level2Previous >= (isMicrosecond ? microseconds : milliseconds) / level2) {
+    if (current - level2Previous >= (isMicrosecond ? MICROSECONDS : MILLISECONDS) / level2) {
       level2Previous = current;
-      led2State = HIGH;
-      digitalWrite(led2Pin, led2State);
+      isLed2On = true;
+      digitalWrite(LED_R, HIGH);
     } else {
-      if (current - level2Previous >= (isMicrosecond ? microseconds : milliseconds) / level2 * ledDutyCycle) {
-        if (led2State == HIGH) {
-          led2State = LOW;
-          digitalWrite(led2Pin, led2State);
+      if (current - level2Previous >= (isMicrosecond ? MICROSECONDS : MILLISECONDS) / level2 * ledDutyCycle) {
+        if (isLed2On == true) {
+          isLed2On = false;
+          digitalWrite(LED_R, LOW);
         }
       }
     }
   }
+  if (isUpdated) {
+    isUpdated = false;
+    digitalWrite(POT_SELECT, LOW);
+    shiftOut(POT_MOSI, POT_CLOCK, MSBFIRST, B00000000);
+    shiftOut(POT_MOSI, POT_CLOCK, MSBFIRST, level3);
+    digitalWrite(POT_SELECT, HIGH);
+    digitalWrite(POT_SELECT, LOW);
+    shiftOut(POT_MOSI, POT_CLOCK, MSBFIRST, B00010000);
+    shiftOut(POT_MOSI, POT_CLOCK, MSBFIRST, level3);
+    digitalWrite(POT_SELECT, HIGH);
+  }

   {
     int index = segmentIndex % 4;
-    byte segment = (0b1111 ^ (1 << ((sizeof(number) / sizeof(int) - 1) - index)));
+    byte segment = (B1111 ^ (1 << ((sizeof(number) / sizeof(int) - 1) - index)));
     byte data = (segment << 4) + number[index];
-    digitalWrite(latchPin, LOW);
-    shiftOut(dataPin, clockPin, MSBFIRST, data);
-    digitalWrite(latchPin, HIGH);
+    digitalWrite(REG_LATCH, LOW);
+    shiftOut(REG_DATA, REG_CLOCK, MSBFIRST, data);
+    digitalWrite(REG_LATCH, HIGH);
     segmentIndex++;
   }
 }

 void registerBlink(int times, int duration) {
-  digitalWrite(latchPin, LOW);
-  shiftOut(dataPin, clockPin, MSBFIRST, 0b00000000);
-  digitalWrite(latchPin, HIGH);
+  digitalWrite(REG_LATCH, LOW);
+  shiftOut(REG_DATA, REG_CLOCK, MSBFIRST, B00000000);
+  digitalWrite(REG_LATCH, HIGH);
   delay(200);
   for (int i = 0; i < times; i++) {
-    digitalWrite(latchPin, LOW);
-    shiftOut(dataPin, clockPin, MSBFIRST, 0b11111111);
-    digitalWrite(latchPin, HIGH);
+    digitalWrite(REG_LATCH, LOW);
+    shiftOut(REG_DATA, REG_CLOCK, MSBFIRST, B11111111);
+    digitalWrite(REG_LATCH, HIGH);
     delay(duration);
-    digitalWrite(latchPin, LOW);
-    shiftOut(dataPin, clockPin, MSBFIRST, 0b00000000);
-    digitalWrite(latchPin, HIGH);
+    digitalWrite(REG_LATCH, LOW);
+    shiftOut(REG_DATA, REG_CLOCK, MSBFIRST, B00000000);
+    digitalWrite(REG_LATCH, HIGH);
     delay(duration);
   }
 }


bugfix

bugfix

--- KISS_OSD/KISS_OSD.ino
+++ KISS_OSD/KISS_OSD.ino
@@ -485,6 +485,10 @@
       }
     }
   }
+  if(recBytes < minBytes)
+  {
+    return false;
+  }
   return true;
 }

@@ -519,6 +523,7 @@

        if(checksum == serialBuf2[recBytes-1])
        {
+         //NewSerial.flushRx();
          minBytesSettings = minBytes;
          fcSettingsReceived = true;
          if(!skipValues)
@@ -1334,12 +1339,15 @@
     if(!fcSettingsReceived)
     {
       NewSerial.write(0x30); // request settings
+      //NewSerial.flushTx();
       ReadFCSettings(fcSettingChanged);
       return;
     }
     else
     {
+      //NewSerial.flushRx();
       NewSerial.write(0x20); // request telemetry
+      //NewSerial.flushTx();
       if(!ReadTelemetry()) return;
     }


Fix template typo in example code

Fix template typo in example code

--- src/examples/iondb_example.ino
+++ src/examples/iondb_example.ino
@@ -7,7 +7,7 @@

 	/* Instantiate your dictionary */
 	Dictionary < int, int > *dict = new
-									SkipList(
+									SkipList<int, int>(
 		key_type_numeric_signed,
 		sizeof(int),
 		sizeof(int),


Fix brake lever parsing

Fix brake lever parsing

--- Event_Printer/Event_Printer.ino
+++ Event_Printer/Event_Printer.ino
@@ -122,10 +122,11 @@
 void handle_MSG_ID_ABS_Control_Module(unsigned char *data, unsigned char length)
 {
     // BRAKE LEVERS
-    unsigned char hnibble7 = HI_NIBBLE(data[6]);
+    unsigned char lnibble7 = LO_NIBBLE(data[6]);
     Serial.print("Brake Levers: ");
-    if( hnibble7 == 0x07 ) Serial.print("Front");
-    else if( hnibble7 == 0x0B ) Serial.print("Rear");
+    if( lnibble7 == 0x07 ) Serial.print("Front");
+    else if( lnibble7 == 0x0B ) Serial.print("Rear");
+    else if( lnibble7 == 0x03 ) Serial.print("None");
     else Serial.print("ERROR-Other");
     Serial.println("");


Cleanup

Cleanup

--- MicroViewStickman.ino
+++ MicroViewStickman.ino
@@ -25,16 +25,10 @@
 int NeckHeight = 4;
 int TotalHeight = LegHeight+BodyHeight+HeadSize;

-//const int LeftLimb = -1;
-//const int RightLimb = 1;
-
-
 void setup() {
-   // put your setup code here, to run once:
    uView.begin();
    uView.clear(ALL);
    uView.display();
-
 }

 void loop() {


Update remotestarter.ino

Update remotestarter.ino

--- source/remotestarter.ino
+++ source/remotestarter.ino
@@ -1,41 +1,68 @@
 // -----------------------------------
-// Starting and Stopping Car Remotely Over the Internet
+// Starting and Stopping Car Remotely Over the Internet with Alexa Integration
 // -----------------------------------
+// Code written by Austin Hable and Chris Hanson
+// EchoPhotonBridge.cpp and EchoPhotonBridge.h written by JeremyProffitt https://github.com/JeremyProffitt/EchoPhotonBridge
+
+// Add the EchoPhontonBridge Library to your code
+#include "EchoPhotonBridge.h"
+
+// Create a new EchoPhotonBridge instance
+EchoPhotonBridge epb;

 // Define the Start and Stop pins
-
 int start = D0;
 int stop = D1;

-void setup()
-{
+// Create a function to call when you tell Alexa to turn something on or off
+int functionOnOff(int device, bool onOff, String rawParameters) {
+
+// Do something when the on or off command is sent. On will start the car and Off with turn off the car.
+if(onOff){
+    digitalWrite(start,LOW);
+    delay(3000);
+    digitalWrite(start,HIGH);
+    return 1;
+}
+
+else {
+    digitalWrite(stop,LOW);
+    delay(3000);
+    digitalWrite(stop,HIGH);
+    return 1;
+}

-   // Pin Configuration
-   pinMode(start, OUTPUT);
-   pinMode(stop, OUTPUT);
+}

-   // Register the Particle Function to work on the web and IFTTT
-   Particle.function("carstarter", remotestarter);
-
-   // Make sure everything is off before running commmands
+void setup() {
+    pinMode(start, OUTPUT);
+    pinMode(stop, OUTPUT);
+
+// Register the Particle Function to work on the web and IFTTT
+    Particle.function("carstarter", remotestarter);
+
+// Make sure everything is off before running commmands
    digitalWrite(start, HIGH);
    digitalWrite(stop, HIGH);

+// This line adds "Turn My Car" to your Alexa,
+// when you say "Alexa Turn My Car On" the functionOnOff is called.
+    epb.addEchoDeviceV2OnOff("Turn My Car", &functionOnOff);
 }

-void loop()
-{
-   // Nothing to do here
+void loop() {
 }

+// This cammand function is used when turning the car on and off from IFTTT or from a custom webpage.
 int remotestarter(String command) {
+
     /* Particle.functions always take a string as an argument and return an integer.
     Since we can pass a string, it means that we can give the program commands on how the function should be used.
     In this case, telling the function "on" will turn the car on and telling it "off" will turn the car off.
     Then, the function returns a value to us to let us know what happened.
     In this case, it will return 1 when starting and stopping the car,
-    and 0 if we received a totally bogus command that didn't do anything to the car.
-    */
+    and 0 if we received a totally bogus command that didn't do anything to the car. */
+

     if (command=="Start Car") {
         digitalWrite(start,LOW);


added debug mode

added debug mode

--- exhaust_sensor_array.ino
+++ exhaust_sensor_array.ino
@@ -21,44 +21,57 @@
 #define SD_pin 10

 // code!
+// #define DEBUG
+#ifdef DEBUG
+#define print   Serial.print
+#define println Serial.println
+#else
+#define print   log_file.print
+#define println log_file.println
+#endif
+
 int sensor_array[6];
 File log_file;

-void print() {
+void print_log() {

-  log_file.print(gps.location.lat(), 6);
-  log_file.print(',');
-  log_file.print(gps.location.lng(), 6);
-  log_file.print(',');
-  log_file.print(gps.time.hour());
-  log_file.print(',');
-  log_file.print(gps.time.minute());
-  log_file.print(',');
-  log_file.print(gps.time.second());
-  log_file.print(',');
-  log_file.print(gps.date.day());
-  log_file.print(',');
-  log_file.print(gps.date.month());
-  log_file.print(',');
-  log_file.print(gps.date.year());
-  log_file.print(',');
-  log_file.print(gps.speed.mph());
-  log_file.print(',');
-  log_file.print(map(CO,  0, 1023, 20,  2000)); //ppm
-  log_file.print(',');
-  log_file.print(map(CO2, 0, 1023,  0, 10000)); //ppm
-  log_file.print(',');
-  log_file.print(map(O3,  0, 1023, 10,  2000)); //ppb
-  log_file.print(',');
-  log_file.print(map(NO,  0, 1023, 50, 10000)); //ppb
-  log_file.print(',');
-  log_file.print(map(TEMP, 0, 1023 , -40, 125)); // celsius
-  log_file.print(',');
-  log_file.print(map(WIND, 0, 1023 , -40, 85)); // celsius
-  log_file.println();
+  print(gps.location.lat(), 6);
+  print(',');
+  print(gps.location.lng(), 6);
+  print(',');
+  print(gps.time.hour());
+  print(',');
+  print(gps.time.minute());
+  print(',');
+  print(gps.time.second());
+  print(',');
+  print(gps.date.day());
+  print(',');
+  print(gps.date.month());
+  print(',');
+  print(gps.date.year());
+  print(',');
+  print(gps.speed.mph());
+  print(',');
+  print(map(CO,  0, 1023, 20,  2000)); //ppm
+  print(',');
+  print(map(CO2, 0, 1023,  0, 10000)); //ppm
+  print(',');
+  print(map(O3,  0, 1023, 10,  2000)); //ppb
+  print(',');
+  print(map(NO,  0, 1023, 50, 10000)); //ppb
+  print(',');
+  print(map(TEMP, 0, 1023 , -40, 125)); // celsius
+  print(',');
+  print(map(WIND, 0, 1023 , -40, 85)); // celsius
+  println();
 }

 void setup() {
+
+  #ifdef DEBUG
+  Serial.begin(9600);
+  #endif

   gps.begin(GPS_BAUD_RATE); //GPS Setup
   SD.begin(SD_PIN);         //SD card start
@@ -66,9 +79,12 @@

 void loop() {

+  #ifdef DEBUG
+  delay(10);
+  #else
   delay(5000);
-
   log_file = SD.open("log.csv", FILE_WRITE);
+  #endif

   // update GPS
   while(gps_port.available()) gps.encode(gps_port.read());
@@ -76,5 +92,5 @@
   //read from sensors
   for(unsigned int i=0; i < 6; ++i) sensor_array[i] = analogRead(i);

-  print();
+  print_log();
 }


clean up fermentation display; closes #42

--- brew-buddy-firmware/src/brew-buddy-firmware.ino
+++ brew-buddy-firmware/src/brew-buddy-firmware.ino
@@ -177,7 +177,7 @@
         lastKnock = fermentationStartTime;

         clearScreen();
-        tft.setCursor(0, 10);
+        tft.setCursor(0, 30);
         tft.setTextColor(ILI9341_YELLOW);
         tft.setTextSize(2);
         tft.print("Fermentation started");
@@ -234,6 +234,8 @@

   if (currentMillis - previousBattMillis > battInterval)
   {
+    previousBattMillis = millis();
+
     int battLevel = getBatteryPercantage();

     displayBattLevel(battLevel);
@@ -508,7 +510,7 @@

 void displayFermentationHeading()
 {
-  tft.setCursor(0, 100);
+  tft.setCursor(0, 110);
   tft.setTextSize(2);
   tft.println("Fermentation Rate");
   tft.println("(in seconds)");
@@ -518,7 +520,7 @@
 {
   unsigned long fermentationDelta = fermentationStartTime - fermentationModeStartTime;

-  tft.setCursor(0, 40);
+  tft.setCursor(0, 60);
   tft.setTextSize(2);
   tft.println("Time to fermentation (hours)");
   tft.println(fermentationDelta / 36000000.00);
@@ -547,8 +549,8 @@

 void displayFermentationRate(long rate)
 {
-  tft.fillRect(0, 80, 240, fermentationRateSize * pixelMultiplier, ILI9341_BLACK);
-  tft.setCursor(0, 80);
+  tft.fillRect(0, 150, 240, fermentationRateSize * pixelMultiplier, ILI9341_BLACK);
+  tft.setCursor(0, 150);
   tft.setTextSize(fermentationRateSize);
   tft.println(rate);
 }


setting template keys and pws

setting template keys and pws

--- cc3200.ino
+++ cc3200.ino
@@ -39,13 +39,15 @@
 #include <PubNub.h>
 #include <aJSON.h>

-static char ssid[] = "UNITE-5B09";    // your network SSID (name)
-static char pass[] = "43071046"; // your network password
+static char ssid[] = "your_wifi_ssid";    // your network SSID (name)
+static char pass[] = "your_wifi_pw"; // your network password

 static int keyIndex = 0;               // your network key Index number (needed only for WEP)

-const static char pubkey[] = "demo-36";
-const static char subkey[] = "demo-36";
+# get your keys at http://www.pubnub.com/developers
+
+const static char pubkey[] = "your_pub_key";
+const static char subkey[] = "your_sub_key";
 const static char channel[] = "hello_ti";
 int sn = 0;
 BMA222 mySensor;


Fixed problem with not known variable name. Updated comments for voltage instead of temperature sensor.

--- arduino/IoTkit/examples/IotKitSendMetricsExample/IotKitSendMetricsExample.ino
+++ arduino/IoTkit/examples/IotKitSendMetricsExample/IotKitSendMetricsExample.ino
@@ -43,7 +43,7 @@

 // create an object of the IoTkit class
 IoTkit iotkit;
-int temp;
+int voltage;
 char buf[112];

 void setup() {
@@ -120,7 +120,7 @@
   delay(5000);
 }

-// reads hardware temp sensor
+// reads hardware voltage sensor
 int getVolt(){
   char scale[4];
   char raw[4];
@@ -131,10 +131,10 @@
   int offset_i;

   FILE *fp_raw;
-  fp_raw = fopen("/sys/bus/iio/devices/iio:device1/in_voltage0_raw", "r");  //read the values from scale, raw and offset files.
-  fgets(raw, 4, fp_raw);                                                    //we need all three values, because the formula for
-  fclose(fp_raw);                                                           //calulating the actual temperature in milli-degrees Celcius
-                                                                            //is: TEMP = (RAW + OFFSET) * SCALE
+  fp_raw = fopen("/sys/bus/iio/devices/iio:device1/in_voltage0_raw", "r");  //read the values from scale and raw
+  fgets(raw, 4, fp_raw);                                                    //the formula for calulating the actual voltage
+  fclose(fp_raw);                                                           //is: VOLTAGE = RAW * SCALE
+
   FILE *fp_scale;
   fp_scale = fopen("/sys/bus/iio/devices/iio:device1/in_voltage_scale", "r");
   fgets(scale, 4, fp_scale);
@@ -142,9 +142,8 @@

   raw_i = atoi(raw);         //we have the values now, but they are in ASCII form-
   scale_i = atoi(scale);     //we need them as integers so we can use them for calculations.
-  //offset_i = atoi(offset);

-  float temp = raw_i  * scale_i;  //Calculate temperature in milli-degrees celcius
-                                  //divide by 1000 to convert to degrees celcius
-  return temp;
+  float voltage = raw_i  * scale_i;  //Calculate voltage
+
+  return voltage;
 }


Update MAIN.ino

Update MAIN.ino


fazendo metodo pra printar dados da struct

--- codigo.ino
+++ codigo.ino
@@ -221,7 +221,25 @@

 int lastButtonState; //@Lanchinho, seria isto aqui o ultimo estado do btn 1 ?

-
+void printDadosBotao(int pressed_button){
+
+    // int codeType;// -1 should be the default
+    // int toggle;  //0 should be the default; The RC5/6 toggle state
+    // unsigned long codeValue; // The code value if not raw
+    // unsigned int rawCodes[RAWBUF]; // The durations if raw
+    // int codeLen; // The length of the code
+
+    Serial.println("Dados Button");
+    Serial.println("codeType:");
+    Serial.println(buttons_list[pressed_button].codeType);
+    Serial.println("toggle:");
+    Serial.println(buttons_list[pressed_button].toggle);
+    Serial.println("codeValue:");
+    Serial.println(buttons_list[pressed_button].codeValue, HEX);
+    Serial.println("codeLen:");
+    Serial.println(buttons_list[pressed_button].codeLen);
+
+}
 //============================================================
 // int lastBtnStateOfBtn2;
 // int lastBtnStateOfBtn3;
@@ -254,6 +272,7 @@
     }
     else if (irrecv.decode(&results))
     {
+        printDadosBotao(0);
         digitalWrite(STATUS_PIN, HIGH);
         storeCode(&results, last_pressed_button);
         irrecv.resume(); // resume receiver