Switched position of MHz character and value

--- src/cyclop_plus_osd/cyclop_plus_osd.ino
+++ src/cyclop_plus_osd/cyclop_plus_osd.ino
@@ -1193,10 +1193,10 @@
   osd( CMD_CLEAR_SCREEN );
   osd( CMD_SET_Y, 0);
   osd( CMD_SET_X, 15 );
+  osd_char(OSD_MHZ);
   osd_string(shortNameOfChannel(currentChannel, buffer));
   osd_char(OSD_SPACE);
   osd_int(getFrequency(currentChannel));
-  osd_char(OSD_MHZ);
   osd_char(OSD_SPACE);
   osd_char(OSD_ANTENNA);
   osd_int(currentRssi);
@@ -1213,10 +1213,10 @@
   osd( CMD_CLEAR_SCREEN );
   osd( CMD_SET_Y, 12);
   osd( CMD_SET_X, 15 );
+  osd_char(OSD_MHZ);
   osd_string(shortNameOfChannel(currentChannel, buffer));
   osd_char(OSD_SPACE);
   osd_int(getFrequency(currentChannel));
-  osd_char(OSD_MHZ);
   osd_char(OSD_SPACE);
   osd_char(OSD_ANTENNA);
   osd_int(currentRssi);


test release

test release

--- Arduino/hardware/V0p2_Main_PCB_REV7_DORM1_and_REV8/REV7RadValve/REV7RadValve.ino
+++ Arduino/hardware/V0p2_Main_PCB_REV7_DORM1_and_REV8/REV7RadValve/REV7RadValve.ino
@@ -114,6 +114,9 @@
 constexpr uint8_t MODE_INT_MASK = (1 << (BUTTON_MODE_L&7));
 constexpr uint8_t MASK_PD = (SERIALRX_INT_MASK | MODE_INT_MASK); // MODE button interrupt (et al).

+// Counter containing current no. of resets.
+static uint8_t resetCount;
+
 ////// SCRATCHSPACE

 // Create scratch space for secure stats TX
@@ -292,7 +295,7 @@
 ////// MESSAGING

 // Managed JSON stats.
-OTV0P2BASE::SimpleStatsRotation<12> ss1; // Configured for maximum different stats.
+OTV0P2BASE::SimpleStatsRotation<13> ss1; // Configured for maximum different stats.

 /******************************************************************************
@@ -362,7 +365,7 @@
 inline void stackCheck()
 {
     const int16_t minsp = OTV0P2BASE::MemoryChecks::getMinSPSpaceBelowStackToEnd();
-#if 1 // && defined(DEBUG)
+#if 1  && defined(DEBUG)
     const uint8_t location = OTV0P2BASE::MemoryChecks::getLocation();
     const uint16_t progCounter = OTV0P2BASE::MemoryChecks::getPC();  // not isr safe
     OTV0P2BASE::serialPrintAndFlush(F("minsp: "));
@@ -426,7 +429,7 @@
 // Will be run after all stats for the current hour have been updated.
 static void endOfDayTasks() {
     // Count down the setback lockout if not finished...  (TODO-786, TODO-906)
-//    OTRadValve::countDownSetbackLockout();  // XXX
+    OTRadValve::countDownSetbackLockout();
 }

@@ -442,17 +445,19 @@
 // as assumed supplied by security layer to remote recipent.
 void bareStatsTX() {

-    OTV0P2BASE::MemoryChecks::resetMinSP();
-//    // Capture heavy stack usage from local allocations here.
+    // Capture heavy stack usage from local allocations here.
     OTV0P2BASE::MemoryChecks::recordIfMinSP();
     const bool neededWaking = OTV0P2BASE::powerUpSerialIfDisabled<>();
     static_assert(OTV0P2BASE::FullStatsMessageCore_MAX_BYTES_ON_WIRE <= STATS_MSG_MAX_LEN, "FullStatsMessageCore_MAX_BYTES_ON_WIRE too big");
     static_assert(OTV0P2BASE::MSG_JSON_MAX_LENGTH+1 <= STATS_MSG_MAX_LEN, "MSG_JSON_MAX_LENGTH too big"); // Allow 1 for trailing CRC.
     OTV0P2BASE::ScratchSpaceL sW(globalWorkSpace.statsTX, sizeof(globalWorkSpace.statsTX));

+    bool sendingJSONFailed = false; // Set true and stop attempting JSON send in case of error.
+
+    uint8_t *const buf = sW.buf;
     // Where to write the real frame content, leaving space for leading
     // frame-length byte for encrypted frame.
-    uint8_t *const realTXFrameStart = sW.buf + 1;
+    uint8_t *const realTXFrameStart = buf + 1;
     // If forcing encryption or if unconditionally suppressed
     // then suppress the "@" ID field entirely,
     // assuming that the encrypted commands will carry the ID, ie in the 'envelope'.
@@ -477,6 +482,15 @@
     ss1.put(NominalRadValve.cumulativeMovementSubSensor);
     // Show state of setback lockout.
     ss1.put(V0p2_SENSOR_TAG_F("gE"), OTRadValve::getSetbackLockout(), true);
+
+    // Show reset counter. Low priority.
+    ss1.put(V0p2_SENSOR_TAG_F("R"), resetCount, true);
+    // Send minimum stack left, saturating at 255 bytes.
+    const size_t curMinSP = OTV0P2BASE::MemoryChecks::getMinSP();
+    const uint8_t txMinSP = (255U >= curMinSP) ? (uint8_t) curMinSP : 255U;
+    ss1.put(V0p2_SENSOR_TAG_F("SP"), txMinSP, true);
+
+
     const uint8_t privacyLevel = OTV0P2BASE::stTXalwaysAll;
     // Redirect JSON output appropriately.
     // Part of sW, directly after the message buffer.
@@ -587,17 +601,17 @@
             // Reset or display ID.
             case 'I': { OTV0P2BASE::CLI::NodeIDWithSet().doCommand(buf, n); break; }
             // Status line stats print and TX.
-            case 'S': {
-                Serial.print(F("Resets: "));
-                const uint8_t resetCount = eeprom_read_byte((uint8_t *)V0P2BASE_EE_START_RESET_COUNT);
-                Serial.print(resetCount);
-                Serial.println();
-                // Show stack headroom.
-                OTV0P2BASE::serialPrintAndFlush(F("SH ")); OTV0P2BASE::serialPrintAndFlush(OTV0P2BASE::MemoryChecks::getMinSPSpaceBelowStackToEnd()); OTV0P2BASE::serialPrintlnAndFlush();
-                // Default light-weight print and TX of stats.
-//                bareStatsTX();  // FIXME No way this won't overflow!
-                break; // Note that status is by default printed after processing input line.
-            }
+//            case 'S': {
+//                Serial.print(F("Resets: "));
+//                const uint8_t resetCount = eeprom_read_byte((uint8_t *)V0P2BASE_EE_START_RESET_COUNT);
+//                Serial.print(resetCount);
+//                Serial.println();
+//                // Show stack headroom.
+//                OTV0P2BASE::serialPrintAndFlush(F("SH ")); OTV0P2BASE::serialPrintAndFlush(OTV0P2BASE::MemoryChecks::getMinSPSpaceBelowStackToEnd()); OTV0P2BASE::serialPrintlnAndFlush();
+//                // Default light-weight print and TX of stats.
+////                bareStatsTX();  // FIXME No way this won't overflow!
+//                break; // Note that status is by default printed after processing input line.
+//            }
             // Switch to FROST mode OR set FROST/setback temperature (even with temp pot available).
             // With F! force to frost and holiday (long-vacant) mode.  Useful for testing and for remote CLI use.
             case 'F': {
@@ -647,7 +661,13 @@
     V0p2Base_serialPrintlnBuildVersion();
     // Count resets to detect unexpected crashes/restarts.
     const uint8_t oldResetCount = eeprom_read_byte((uint8_t *)V0P2BASE_EE_START_RESET_COUNT);
+    resetCount = oldResetCount + 1;
     eeprom_write_byte((uint8_t *)V0P2BASE_EE_START_RESET_COUNT, 1 + oldResetCount);
+#if 0  // Print reset count. Intended for testing purposes.
+    OTV0P2BASE::serialPrintAndFlush(F("\rResets: "));
+    OTV0P2BASE::serialPrintAndFlush(oldResetCount);
+    OTV0P2BASE::serialPrintlnAndFlush();
+#endif

     // Have 32678Hz clock at least running before going any further.
     // Check that the slow clock is running reasonably OK, and tune the fast one to it.
@@ -709,10 +729,6 @@
     // Initialise sensors with stats info where needed.
     updateSensorsFromStats();

-    OTV0P2BASE::MemoryChecks::resetMinSP();  // XXX
-    OTV0P2BASE::MemoryChecks::recordIfMinSP(1);
-    stackCheck();
-
     // Do early 'wake-up' stats transmission if possible // XXX
     // when everything else is set up and ready and allowed (TODO-636)
     // including all set-up and inter-wiring of sensors/actuators.
@@ -748,8 +764,6 @@

 void loop()
 {
-    OTV0P2BASE::MemoryChecks::resetMinSP();  // XXX
-    OTV0P2BASE::MemoryChecks::recordIfMinSP(2);
     stackCheck();

     // Main loop for OpenTRV radiator control.
@@ -832,7 +846,7 @@
             // Tasks that must be run every minute.
             ++minuteCount; // Note simple roll-over to 0 at max value.
             // Force to user's programmed schedule(s), if any, at the correct time.
-            Scheduler.applyUserSchedule(&valveMode, OTV0P2BASE::getMinutesSinceMidnightLT());  // XXX
+            Scheduler.applyUserSchedule(&valveMode, OTV0P2BASE::getMinutesSinceMidnightLT());
             // Ensure that the RTC has been persisted promptly when necessary.
             OTV0P2BASE::persistRTC();
             // Run hourly tasks at the end of the hour.


command parser timeout

command parser timeout

--- polar-scanner.ino
+++ polar-scanner.ino
@@ -10,7 +10,8 @@
  * **** **** **** **** **** ****/

 #define BPS_HOST 9600
-#define COMMS_BUFFER_SIZE 256
+#define COMMS_BUFFER_SIZE 32
+#define SERIAL_HOST_DELAY_MS 10000

 /*
  * ultra sonic telemeter mesure
@@ -150,15 +151,19 @@
  * userIO
  */
 char * userInput(char * message) {
-	char * input = NULL;
+	unsigned long timeLoopStart,timeLoop;
 	int nread = 0;
-	Serial.print(message);
-	while (!(nread = Serial.readBytes(commsBuffer, COMMS_BUFFER_SIZE)));
-	if (nread == COMMS_BUFFER_SIZE)
-		return input; // buffer overflow
+	if (message)
+		Serial.print(message);
+	timeLoopStart = timeLoop = millis();
+	// Serial timeout triggers on full commsBuffer, just wait for first command
+	while (nread == 0 && timeLoop - timeLoopStart < SERIAL_HOST_DELAY_MS) {
+		// drop older contents on buffer overflow
+		while ((nread = Serial.readBytes(commsBuffer, COMMS_BUFFER_SIZE)) == COMMS_BUFFER_SIZE);
+		timeLoop = millis();
+	}
 	commsBuffer[nread] = 0;
-	input = commsBuffer;
-	return input;
+	return nread == 0 ? NULL : commsBuffer;
 }

 /*
@@ -179,8 +184,10 @@
 			break;

 		case IN_CMD:
-			if (!(input = userInput("CMD: ")))
+			if (!(input = userInput("CMD: "))) {
+				newState = IN_CMD;
 				break;
+			}
 			if (!strcmp(input,"SERVO"))
 				newState = IN_SERVO;
 			else if (!strcmp(input,"STEPPER"))
@@ -191,7 +198,7 @@

 		case IN_SERVO:
 			if (!(input = userInput("ANGLE: ")))
-				break;
+				while (!(input = userInput(NULL)));
 			value = atoi(input);
 			servoCommand(value);
 			newState = IN_CMD;
@@ -199,7 +206,7 @@

 		case IN_STEPPER:
 			if (!(input = userInput("STEPS: ")))
-				break;
+				while (!(input = userInput(NULL)));
 			value = atoi(input);
 			stepperCommand(value);
 			newState = IN_CMD;


print stats on serial

print stats on serial

--- main/main.ino
+++ main/main.ino
@@ -77,6 +77,9 @@

 tCAN emtpyMessage;

+unsigned long goodDataCount = 0;
+unsigned long badDataCount = 0;
+
 void setup() {

   lcd.createChar(0, fill1);
@@ -102,12 +105,11 @@

   if(messageReceived == 1) {
     if(currentMillis - lastMillis >= interval) {
-      Serial.println("===screen refresh===");
       lastMillis = currentMillis;
       lcd.setCursor(4, 2);
       lcd.print(tgt);
-      Serial.print("===screen refresh===");
-      Serial.println(tgt);
+      //Serial.println(tgt);
+      Serial.println((double)badDataCount / (double)goodDataCount);

     }
     messageReceived = 0;
@@ -143,22 +145,25 @@
   //Serial.println("trying to get data");
   if(mcp2515_check_message()) {

-    Serial.print("there is a message ");
+    //Serial.print("there is a message ");
     mcp2515_get_message(message);

     if(message->data[0] >= 100) {
         tgt = (double)message->data[0] / 10.0;
-        Serial.print("good data ");
-        Serial.println(tgt);
+        //Serial.print("good data ");
+        //Serial.println(tgt);
+        goodDataCount++;
     }
     else {
-      Serial.println("bad data ");
+      ///Serial.println("bad data ");
+      badDataCount++;
     }

     messageReceived = 1;
   }
   else {
     messageReceived = 0;
+    //Serial.println("no data");
   }

 }


Update main.ino

Update main.ino

--- main/main.ino
+++ main/main.ino
@@ -18,9 +18,10 @@
 int ppqn = 0;

 void setup(){
+
 Serial.begin(115200);

-for (int i=2; i<=7; i++){pinMode(i, INPUT);} // Set Inputs
+for (int i=2; i<=9; i++){pinMode(i, INPUT);} // Set Inputs

 for (int i=22; i<=35; i++){pinMode(i, INPUT);} // Set Inputs

@@ -28,6 +29,8 @@

 for (int i=36; i<=52; i++){digitalWrite(i, HIGH);delay(250);} // Toggle Leds ON
 for (int i=36; i<=52; i++){digitalWrite(i, LOW);delay(250);} // Toggle Leds OFF
+
+attachInterrupt(JogWheelPinA, sendJogWheel, RISING); // interrupts
 }

 void loop(){
@@ -195,7 +198,7 @@
 }

 void setMidiOut(){
-
+
 valSongSwitch = digitalRead(SongSwitch); // Read Analog Input
  if (lastSongSwitch != valSongSwitch){ // Only send Midi CC if changed is detected
   controlChange(MidiChannel, 40, valSongSwitch); // Send CC
@@ -318,3 +321,40 @@
   }

 }
+
+void sendJogWheel()
+{
+ // read both inputs
+  int a = digitalRead(JogWheelPinA);
+  int b = digitalRead(JogWheelPinB);
+
+  if (a == b )
+  {
+    // b is leading a (counter-clockwise)
+    valJogWheel--;
+    currentDirection = COUNTER_CLOCKWISE;
+  }
+  else
+  {
+    // a is leading b (clockwise)
+    valJogWheel++;
+    currentDirection = CLOCKWISE;
+  }
+
+  // track 0 to 400
+  valJogWheel = valJogWheel % CPR;
+
+  mappedvalJogWheel = map(abs(valJogWheel), 0, JogWheelMaxval, 0, 127);
+
+  controlChange(MidiChannel, 63, 127); // Send CC For JogWheel Activity
+  JogWheelActive = 1;
+    if (currentDirection = CLOCKWISE){
+     controlChange(MidiChannel, 61, mappedvalJogWheel); // Send CC For JogWheel Direction
+      }
+     if (currentDirection = COUNTER_CLOCKWISE){
+     controlChange(MidiChannel, 62, mappedvalJogWheel); // Send CC For JogWheel Direction
+      }
+  MidiUSB.flush(); // Be sure CC is Send
+  valJogWheel = 0;
+  }
+}


report roof speed

report roof speed

--- KomaRoof.ino
+++ KomaRoof.ino
@@ -345,6 +345,8 @@
     message += ".";
     message += (int)(batteryVoltage*10) % 10;
     message += (int)(roundf(batteryVoltage*100)) % 10;
+    message += ",SPEED=";
+    message += roofSpeed;
     if (temperature != (float)DEVICE_DISCONNECTED_C) {
         message += ",TEMP1=";
         message += (int)(temperature);


Demo.ino: improved the top comment.

Demo.ino: improved the top comment.

--- examples/Demo/Demo.ino
+++ examples/Demo/Demo.ino
@@ -8,8 +8,8 @@
 // connected to the Romi 32U4.  If you cannot see any text on the
 // LCD, try rotating the contrast potentiometer.
 //
-// To compile this demo program, you will need to install the
-// LSM6 and LIS3MDL libraries:
+// To run this sketch, you will need to install the LSM6 and
+// LIS3MDL libraries:
 //
 // https://github.com/pololu/lsm6-arduino
 // https://github.com/pololu/lis3mdl-arduino


Enhanced beacon.ino with GPS hook

Enhanced beacon.ino with GPS hook

--- ESP32/beacon/beacon.ino
+++ ESP32/beacon/beacon.ino
@@ -36,10 +36,15 @@
     SurfaceMiningEquipmentBEACON = 4
 };

-// BEACON WIRE PACKET FORMAT VERSION 2
-// Deisgned per Anurag, Gosh, Bandyopadhyay, "GPS based Vehicular Collision Warning System using IEEE 802.15.4 MAC/PHY Standard"
+// BEACON WIRE PACKET FORMAT (VERSION 2)
+// With five character local name, there remain two spare bytes (according to "nRF Connect" android app)
+// Format aligned with... Anurag, Gosh, Bandyopadhyay, "GPS based Vehicular Collision Warning System using IEEE 802.15.4 MAC/PHY Standard"
+char * localName = "C9999";
+int LOCALNAMESIZE = sizeof(localName);      //use for strncpy()
+#define GPS_SCALE 100000
+
 typedef union
-{   uint8_t       raw[27];
+{   uint8_t           raw[27];
     struct
     {   uint16_t      companyID ;                   // Ref https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers
         uint16_t      gpsForwardBearing;            // Azimuth
@@ -51,37 +56,33 @@
         uint8_t       sideExclusionZoneDistance;    // W, scale 1m
         uint8_t       packetVersion;                // This is siteBKNS Packet Format Version 2
     } fields;
-}custom_data_t;
+}beacon_data_t;

-// BEACON DUMMY DATA TO OBSERVE WIRE PROTOCOL DATA PACKING
-// with five character local name, there remain two spare bytes (according to "nRF Connect" android app)
-char * localName = "C9999";
-int LOCALNAMESIZE = sizeof(localName);
-custom_data_t custom_data =
-{ .fields =
-  {   .companyID = 0xFFFF,                      // Reserved by Bluetooth Specification for internal testing
-      .gpsForwardBearing=0x1111,                // Azimuth, scale 1 degree
-      .gpsLatitute= 0x22222222,                 // X, scale 100000/0.00001m
-      .gpsLongitude=0x33333333,                 // Y, scale 100000/0.00001m
-      .gpsForwardSpeed=0x44,
-      .forwardExclusionZoneDistance = 0xAA,     // F, scale 1m, max 256
-      .rearExclusionZoneDistance = 0xBB,        // L, scale 1m, max 256
-      .sideExclusionZoneDistance = 0xCC,        // W, scale 1m, max 256
-      .packetVersion = 0x02                     // This is siteBKNS packet format VERSION 2
-  }
-};
+// BEACON DEFAULT DATA CAN BE USED TO OBSERVE ALIGNMENT PACKING OF WIRE PROTOCOL
+beacon_data_t myBeaconData =
+  { .fields =
+      {     .companyID                    = 0xFFFF,    //reserved by Bluetooth Specification for internal testing
+            .gpsForwardBearing            = 0x1111,
+            .gpsLatitute                  = 0x22222222,
+            .gpsLongitude                 = 0x33333333,
+            .gpsForwardSpeed              = 0x44,
+            .forwardExclusionZoneDistance = 0xAA,
+            .rearExclusionZoneDistance    = 0xBB,
+            .sideExclusionZoneDistance    = 0xCC,
+            .packetVersion                = 2
+      }
+  };

 // BLE GAP ADVERTISING CONFIGURATION
-
-static esp_ble_adv_data_t _adv_config = {
+static esp_ble_adv_data_t advertisement_config = {
         .set_scan_rsp        = false,
         .include_name        = true,
         .include_txpower     = true,      // !!!! TX-power can help with backup distance calculation in GPS blackspots
         .min_interval        = 512,
         .max_interval        = 1024,
         .appearance          = 0,
-        .manufacturer_len    = 0,
-        .p_manufacturer_data = NULL,
+        .manufacturer_len    = sizeof(beacon_data_t),
+        .p_manufacturer_data = myBeaconData.raw,    //update myBeaconData then call esp_ble_gap_config_adv_data(&advertisement_config)
         .service_data_len    = 0,
         .p_service_data      = NULL,
         .service_uuid_len    = 0,
@@ -89,7 +90,7 @@
         .flag                = (ESP_BLE_ADV_FLAG_GEN_DISC|ESP_BLE_ADV_FLAG_BREDR_NOT_SPT)
 };

-static esp_ble_adv_params_t _adv_params = {
+static esp_ble_adv_params_t advertisement_params = {
         .adv_int_min         = 512,
         .adv_int_max         = 1024,
         .adv_type            = ADV_TYPE_NONCONN_IND,
@@ -100,20 +101,18 @@
         .adv_filter_policy   = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY,
 };

-uint32_t counter = 0;
+/////////////////////////
+// BLE SUPPORT FUNCTIONS

-// BLE FUNCTIONS
-
-static void _on_gap(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param){
+static void
+_on_gap(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param){
     if(event == ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT){
-        esp_ble_gap_start_advertising(&_adv_params);
-        Serial.println();
+        esp_ble_gap_start_advertising(&advertisement_params);
     }
-    Serial.print(".");
-    Serial.print(counter);
 }

-static bool _init_gap(const char * name){
+static bool
+initialize_ble_gap(const char * name){
     if(!btStarted() && !btStart()){
         log_e("btStart failed");
         return false;
@@ -139,9 +138,7 @@
         return false;
     }

-    _adv_config.p_manufacturer_data = custom_data.raw;
-    _adv_config.manufacturer_len = sizeof(custom_data_t);
-    if(esp_ble_gap_config_adv_data(&_adv_config)){
+    if(esp_ble_gap_config_adv_data(&advertisement_config)){
         log_e("gap_config_adv_data failed");
         return false;
     }
@@ -154,9 +151,31 @@
     return true;
 }

-// ARDUINO FUNCTIONS
+///////////////////////////
+// GPS INPUT PARSING

-void setup() {
+void
+gps_read_into( beacon_data_t * beaconData)
+{
+    static long counter = 0;  //example only
+    counter = counter + 1;    //example only
+    Serial.println(counter);
+    //@Nancy, can you fill out the following with real GPS info?
+    beaconData->fields.gpsForwardBearing            = counter;
+    beaconData->fields.gpsLatitute                  = beaconData->fields.gpsLatitute;  // times by GPS_SCALE;
+    beaconData->fields.gpsLongitude                 = beaconData->fields.gpsLongitude; // times by GPS_SCALE;
+    beaconData->fields.gpsForwardSpeed              = beaconData->fields.gpsForwardSpeed;
+    beaconData->fields.forwardExclusionZoneDistance = beaconData->fields.forwardExclusionZoneDistance;
+    beaconData->fields.rearExclusionZoneDistance    = beaconData->fields.rearExclusionZoneDistance;
+    beaconData->fields.sideExclusionZoneDistance    = beaconData->fields.sideExclusionZoneDistance;
+}
+
+
+//////////////////////////////
+// ARDUINO SUPPORT FUNCTIONS
+
+void
+setup() {
     Serial.begin(115200);
     Serial.setDebugOutput(true);
     pinMode(LED_BUILTIN, OUTPUT);
@@ -164,13 +183,14 @@
     Serial.println(ESP.getSdkVersion());
     //esp_log_level_set("*", ESP_LOG_VERBOSE);

-    //ble.begin("WEMOS SimpleBLE");
-    _init_gap("C9999");
+    initialize_ble_gap("C9999");
  }

-void loop() {
-    counter = counter + 1;
-    if(esp_ble_gap_config_adv_data(&_adv_config))
+
+void
+loop() {
+    gps_read_into( &myBeaconData );
+    if(esp_ble_gap_config_adv_data(&advertisement_config))
     {   log_e("gap_config_adv_data failed");
         exit(1);
     }


Minor textual cleanups.

Minor textual cleanups.

--- JnGeneral/JnGeneral.ino
+++ JnGeneral/JnGeneral.ino
@@ -47,9 +47,9 @@
     { UNIT_TEMP,     "Temperature", "C" },
     { UNIT_VOLT,     "Voltage", "V" },
     { UNIT_OHM,      "Resistance", "ohm" },
-    { UNIT_SCALAR,   "(no unit)", "" },
-    { UNIT_TESLA,    "Magnetic field (Tesla)", "T" }, // 10^-4 T = 1 gauss
-    { UNIT_PASCAL,   "Pressure (Pascal)", "Pa" },
+    { UNIT_SCALAR,   "Scalar", "" },
+    { UNIT_TESLA,    "Magnetic field", "T" }, // 10^-4 T = 1 gauss
+    { UNIT_PASCAL,   "Pressure", "Pa" },
 };

 static int numUnits = sizeof(units) / sizeof(units[0]);
@@ -199,24 +199,24 @@
                         Serial.println("Port already used");
                         break;
                     }
-                 }
-                 if(i==numPlugs) {
-                     if(numPlugs == MAX_PLUGS) {
-                         Serial.println("Too many plugs defined");
-                         break;
-                     }
-                     memset(&plugs[numPlugs], 0, sizeof(Plug));
-                     plugs[numPlugs].port = port;
-                     plugs[numPlugs].device_id = dev->device_id;
-                     plugs[numPlugs].period = SCALE(6,2);  // 600 * tenths of seconds = 1 minute
-                     for(int k=0; k<dev->num_measurements; k++) {
-                         plugs[numPlugs].scale[k] = dev->measurements[k].scale;
-                     }
-                     numPlugs++;
-                     Serial.println("Device added.");
-                     init_measure(plugs[numPlugs-1]);
-                 }
-                 saveConfig();
+                }
+                if(i==numPlugs) {
+                    if(numPlugs == MAX_PLUGS) {
+                        Serial.println("Too many plugs defined");
+                        break;
+                    }
+                    memset(&plugs[numPlugs], 0, sizeof(Plug));
+                    plugs[numPlugs].port = port;
+                    plugs[numPlugs].device_id = dev->device_id;
+                    plugs[numPlugs].period = SCALE(6,2);  // 600 * tenths of seconds = 1 minute
+                    for(int k=0; k<dev->num_measurements; k++) {
+                        plugs[numPlugs].scale[k] = dev->measurements[k].scale;
+                    }
+                    numPlugs++;
+                    Serial.println("Device added.");
+                    init_measure(plugs[numPlugs-1]);
+                }
+                saveConfig();
                 scheduler.timer(TASK_ANNOUNCE, 0);
             }
             break;
@@ -339,7 +339,6 @@
         Serial.print(devices[i].name);
         Serial.print(", measures: ");
         for(int j=0; j < devices[i].num_measurements; j++) {
-            printScale(devices[i].measurements[j].scale);
             Unit *unit = getUnit(devices[i].measurements[j].unit);
             if(!unit)
                 Serial.print("(Unknown)");
@@ -371,9 +370,11 @@
                 Serial.print("(Unknown)");
             else {
                 Serial.print(unit->descr);
+                Serial.print(" (");
+                printScale(plugs[i].scale[j]);
                 Serial.print(" ");
-                printScale(plugs[i].scale[j]);
                 Serial.print(unit->unitname);
+                Serial.print(") ");
             }
             Serial.print(", ");
         }
@@ -550,7 +551,7 @@

 void setup () {
     Serial.begin(57600);
-    Serial.print("\r\n[JeeNode General]\r\n");
+    Serial.println("\r\n[JeeNode General]");
     loadRF12Config();
     loadConfig();


refatorando os botoes (structs) para terem dados dos estados do botao apertado e qual o pin relacionado.

--- codigo.ino
+++ codigo.ino
@@ -20,7 +20,7 @@
 int RECV_PIN = 11;
 int FIRST_BUTTON_PIN = 12;
 //================================================================================================================================
-// int SECOND_BUTTON_PIN = 3; //@Lanchinho : nao necessariamente neste pino/ casa, pode ser qlqer outra que esteja livre
+int SECOND_BUTTON_PIN = 2;
 // int THIRD_BUTTON_PIN = 4;  //@Lanchinho: Vou deixar todas as cagadas, digo alterações feitas por mim separadas por um "========="
 //================================================================================================================================
 int STATUS_PIN = 13;
@@ -34,6 +34,9 @@
 typedef struct Button_Info{
     int codeType;// -1 should be the default
     int toggle;  //0 should be the default; The RC5/6 toggle state
+    int button_pin; //the button pin of this button
+    int button_state; //the actual state of this button, if been pressed or not
+    int last_button_state; //the last state, to verify if this button has been released or not
     unsigned long codeValue; // The code value if not raw
     unsigned int rawCodes[RAWBUF]; // The durations if raw
     int codeLen; // The length of the code
@@ -44,10 +47,15 @@
 //=====================
 int last_pressed_button = 0; //por default o ultimo botao pressionado vai ser o primeiro

-Button_Info button_one = { -1, 0 };// inicializando codeType =-1 e toggle=0;
+// inicializando codeType =-1 e toggle=0, e o button bin como o do FIRST_BUTTON_PIN;
+//button_state = 0, e last_button_state =0 tmb, indicando que estava sem apertar e continua assim.
+Button_Info button_one = { -1, 0, FIRST_BUTTON_PIN, 0, 0 };
+// inicializando codeType =-1 e toggle=0, e o button bin como o do SECOND_BUTTON_PIN;
+//button_state = 0, e last_button_state =0 tmb, indicando que estava sem apertar e continua assim.
+Button_Info button_two = { -1, 0, SECOND_BUTTON_PIN, 0, 0 };

 //lista dos botoes
-Button_Info buttons_list[1] = { button_one };
+Button_Info buttons_list[2] = { button_one, button_two };

 //=====================
 //VARIAVEIS GLOBAIS - FIM
@@ -59,17 +67,11 @@
     Serial.begin(9600);
     irrecv.enableIRIn(); // Start the receiver
     pinMode(FIRST_BUTTON_PIN, INPUT);
-    // pinMode(SECOND_BUTTON_PIN, INPUT);
+    pinMode(SECOND_BUTTON_PIN, INPUT);
     // pinMode(THIRD_BUTTON_PIN, INPUT);
     pinMode(STATUS_PIN, OUTPUT);
 }

-// Storage for the recorded code
-// int codeType = -1; // The type of code
-// unsigned long codeValue; // The code value if not raw
-// unsigned int rawCodes[RAWBUF]; // The durations if raw
-// int codeLen; // The length of the code
-// int toggle = 0; // The RC5/6 toggle state

 // Stores the code for later playback
@@ -219,15 +221,8 @@

-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:");
@@ -241,32 +236,45 @@

 }
 //============================================================
+// int lastButtonState;
 // int lastBtnStateOfBtn2;
 // int lastBtnStateOfBtn3;
 //============================================================

+int check_button_released(int button_index){
+    return buttons_list[button_index].last_button_state == HIGH && buttons_list[button_index].button_state == LOW;
+}
+
+int check_button_pressed(int button_index){
+    return buttons_list[button_index].button_state;
+}
+
+
+
 void loop()
 {
     // If button pressed, send the code.
-    int firstButtonState = digitalRead(FIRST_BUTTON_PIN);

     //========================================================
+    buttons_list[0].button_state = digitalRead(FIRST_BUTTON_PIN);
+    buttons_list[1].button_state = digitalRead(SECOND_BUTTON_PIN);
+
     // int secondButtonState = digitalRead(SECOND_BUTTON_PIN);
     // int thirdButtonState = digitalRead(THIRD_BUTTON_PIN);
     //========================================================

-    if (lastButtonState == HIGH && firstButtonState == LOW)
+    if (check_button_released(0))
     {
         Serial.println("Released");
         irrecv.enableIRIn(); // Re-enable receiver
     }

-    if (firstButtonState)
+    if (check_button_pressed(0))
     {
         last_pressed_button = 0; //marca o primeiro botao como sendo o pressionado
         Serial.println("Pressed, sending");
         digitalWrite(STATUS_PIN, HIGH);
-        sendCode(lastButtonState == firstButtonState, last_pressed_button);
+        sendCode(buttons_list[0].last_button_state == buttons_list[0].button_state, last_pressed_button);
         digitalWrite(STATUS_PIN, LOW);
         delay(50); // Wait a bit between retransmissions
     }
@@ -278,61 +286,7 @@
         irrecv.resume(); // resume receiver
         digitalWrite(STATUS_PIN, LOW);
     }
-    lastButtonState = firstButtonState;
-
-//==========================================================================
-//Btn2
-    // if (lastBtnStateOfBtn2 == HIGH && secondButtonState == LOW)
-    // {
-    //     Serial.println("Released");
-    //     irrecv.enableIRIn(); // Re-enable receiver
-    // }
-
-    // if (secondButtonState)
-    // {
-    //     Serial.println("Pressed, sending");
-    //     digitalWrite(STATUS_PIN, HIGH);
-    //     sendCode(lastBtnStateOfBtn2 == secondButtonState);
-    //     digitalWrite(STATUS_PIN, LOW);
-    //     delay(50); // Wait a bit between retransmissions
-    // }
-    // else if (irrecv.decode(&results))
-    // {
-    //     digitalWrite(STATUS_PIN, HIGH);
-    //     storeCode(&results);
-    //     irrecv.resume(); // resume receiver
-    //     digitalWrite(STATUS_PIN, LOW);
-    // }
-    // lastBtnStateOfBtn2 = lastBtnStateOfBtn2;
-
-    // //Btn 3
-    // if (lastBtnStateOfBtn3 == HIGH && thirdButtonState == LOW)
-    // {
-    //     Serial.println("Released");
-    //     irrecv.enableIRIn(); // Re-enable receiver
-    // }
-
-    // if (thirdButtonState)
-    // {
-    //     Serial.println("Pressed, sending");
-    //     digitalWrite(STATUS_PIN, HIGH);
-    //     sendCode(lastBtnStateOfBtn3 == thirdButtonState);
-    //     digitalWrite(STATUS_PIN, LOW);
-    //     delay(50); // Wait a bit between retransmissions
-    // }
-    // else if (irrecv.decode(&results))
-    // {
-    //     digitalWrite(STATUS_PIN, HIGH);
-    //     storeCode(&results);
-    //     irrecv.resume(); // resume receiver
-    //     digitalWrite(STATUS_PIN, LOW);
-    // }
-    // lastBtnStateOfBtn3 = thirdButtonState;
-//===========================================================
-
-
-
-
-
-
-}
+    buttons_list[0].last_button_state = buttons_list[0].button_state;
+
+
+}


Fix compile issue

Fix compile issue

Fixes Github issue #16
Thanks to [katkothaza](https://github.com/katkothaza).

--- examples/SoftWire_MLX90614/SoftWire_MLX90614.ino
+++ examples/SoftWire_MLX90614/SoftWire_MLX90614.ino
@@ -55,9 +55,9 @@
 void exitPWM(void)
 {
 	// Make SMBus request to force SMBus output instead of PWM
-	SoftWire::setSclLow(&i2c);
+	SoftWire::sclLow(&i2c);
 	delay(3); // Must be > 1.44ms
-	SoftWire::setSclHigh(&i2c);
+	SoftWire::sclHigh(&i2c);
 	delay(2);
 }


Deleted

Deleted

--- Nauteelvs/Nauteelvs.ino
+++ Nauteelvs/Nauteelvs.ino
@@ -1,533 +0,0 @@
-#include <RTClib.h>
-#include "arduinoFFT.h"
-#include <Wire.h>
-#include <Timer32.h>
-#include <string.h>
-#include <SD.h>
-#include <SPI.h>
-#include "Fishino.h"
-#include <WebSocket.h>
-#include <Arduino.h>
-
-
-//variabili websocket
-#ifndef MYNET_H
-// SSID della rete WiFi
-#define MY_SSID  "Fishino32"
-
-// PASSWORD of network.
-#define MY_PASS ""
-
-// 'IP desiderato per il fishino
-#define IPADDR  192, 168, 1, 251
-#endif
-
-#ifndef _FISHINO32_
-const int SD_CS = 4;
-#else
-const int SD_CS = SDCS;
-#endif
-
-#ifdef IPADDR
-IPAddress ip(IPADDR);
-#endif
-
-// Enabe debug tracing to Serial port.
-#define DEBUG
-
-
-arduinoFFT FFT = arduinoFFT();
-const int samples = 64; //campioni
-const double sampling = 200;  //frequenza di campionamento
-uint8_t exponent;
-double vRealx[samples];
-double vImagx[samples];
-double vRealy[samples];
-double vImagy[samples];
-double vRealz[samples];
-double vImagz[samples];
-double vReala[samples];
-double vImaga[samples];
-int i = 0;
-int j = 0;
-double jr[samples];
-double ji[samples];
-double freq[200/2];
-
-long int ti;
-volatile bool intFlag=false;
-
-
-#define SIZE 8 //numero di FFT calcolate prima di scrivere su SD
-const int chipSelect_SD_default = SDCS;
-const int chipSelect_SD = chipSelect_SD_default;
-String data= "";
-#if defined(ARDUINO_ARCH_SAMD)
-   #define Serial SerialUSB
-#endif
-RTC_Millis rtc;
-char nome_file[17];
-char **data_base;
-
-
-WebSocketServer wsServer;
-uint8_t mac[WL_MAC_ADDR_LENGTH]={0x11,0x22,0x33,0x44,0x55,0x66};
-
-
-#define SCL_INDEX 0x00
-#define SCL_TIME 0x01
-#define SCL_FREQUENCY 0x02
-
-
-#define    MPU9250_ADDRESS            0x68
-
-#define    ACC_FULL_SCALE_2_G        0x00
-#define    ACC_FULL_SCALE_4_G        0x08
-#define    ACC_FULL_SCALE_8_G        0x10
-#define    ACC_FULL_SCALE_16_G       0x18
-
-#define   a   0
-#define   x   1
-#define   y   2
-#define   z   3
-
-
-// This function read Nbytes bytes from I2C device at address Address.
-// Put read bytes starting at register Register in the Data array.
-void I2Cread(uint8_t Address, uint8_t Register, uint8_t Nbytes, uint8_t* Data)
-{
-  // Set register address
-  Wire.beginTransmission(Address);
-  Wire.write(Register);
-  Wire.endTransmission();
-
-  // Read Nbytes
-  Wire.requestFrom(Address, Nbytes);
-  uint8_t index=0;
-  while (Wire.available())
-    Data[index++]=Wire.read();
-}
-
-// Write a byte (Data) in device (Address) at register (Register)
-void I2CwriteByte(uint8_t Address, uint8_t Register, uint8_t Data)
-{
-  // Set register address
-  Wire.beginTransmission(Address);
-  Wire.write(Register);
-  Wire.write(Data);
-  Wire.endTransmission();
-}
-
-void callback()
-{
-  intFlag=true;
-}
-
-
-void onConnect(WebSocket &socket)
-{
-  Serial.println("onConnect called");
-}
-
-// It will be called by the server when a data frame is received.
-void onData(WebSocket &socket, char* dataString, byte frameLength)
-{
-  #ifdef DEBUG
-   Serial.print("Got data: ");
-   Serial.write((unsigned char*)dataString, frameLength);
-   Serial.println();
-  #endif
-
-  // Just echo back data for fun.
-  socket.send(dataString, strlen(dataString));
-}
-
-void onDisconnect(WebSocket &socket) {
-  Serial.println("onDisconnect called");
-}
-
-
-void getFileName(char *name)
-{
-  DateTime now = rtc.now();
-  sprintf(name, "%d", now.year());
-  int temp= now.month();
-  if(temp > 9)
-  {
-    sprintf(name+4, "%d", temp);
-  }
-  else
-  {
-    name[4]= '0';
-    sprintf(name+5, "%d", temp);
-  }
-  temp= now.day();
-  if(temp > 9)
-  {
-    sprintf(name+6, "%d", temp);
-  }
-  else
-  {
-    name[6]= '0';
-    sprintf(name+7, "%d", temp);
-  }
-  temp= now.hour();
-  if(temp > 9)
-  {
-    sprintf(name+8, "%d", temp);
-  }
-  else
-  {
-    name[8]= '0';
-    sprintf(name+9, "%d", temp);
-  }
-  temp= now.minute();
-  if(temp > 9)
-  {
-    sprintf(name+10, "%d", temp);
-  }
-  else
-  {
-    name[10]= '0';
-    sprintf(name+11, "%d", temp);
-  }
-  temp= now.second();
-  if(temp > 9)
-  {
-    sprintf(name+12, "%d", temp);
-  }
-  else
-  {
-    name[12]= '0';
-    sprintf(name+13, "%d", temp);
-  }
-  name[14]= '.';
-  name[15]= 't';
-  name[16]= 'x';
-  name[17]= 't';
-  Serial.println(name);
-}
-/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-
-
-void setup()
-{
-  Wire.begin();
-  #ifdef DEBUG
-    Serial.begin(115200);
-  #endif
-  //while(!Serial);
-
-  rtc.begin(DateTime(F(__DATE__), F(__TIME__)));
-
-  Fishino.setApMAC(mac);
-
-  // initialize SPI:
-  SPI.begin();
-  SPI.setClockDivider(SPI_CLOCK_DIV2);
-
-  // reset and test wifi module
-  Serial << F("Resetting Fishino...");
-  while(!Fishino.reset())
-  {
-    Serial << ".";
-    delay(500);
-  }
-  Serial << F("OK\r\n");
-
-  // set PHY mode 11G
-  Fishino.setPhyMode(PHY_MODE_11G);
-
-  // setup SOFT AP mode
-  // imposta la modalitè SOFTAP
-  Serial << F("Setting mode SOFTAP_MODE\r\n");
-  Fishino.setMode(SOFTAP_MODE);
-
-  // stop AP DHCP server
-  Serial << F("Stopping DHCP server\r\n");
-  Fishino.softApStopDHCPServer();
-
-  // setup access point parameters
-  Serial << F("Setting AP IP info\r\n");
-  Fishino.setApIPInfo(ip, ip, IPAddress(255, 255, 255, 0));
-
-  Serial << F("Setting AP WiFi parameters\r\n");
-  Fishino.softApConfig(F(MY_SSID), F(MY_PASS), 1, false);
-
-  // restart DHCP server
-  Serial << F("Starting DHCP server\r\n");
-  Fishino.softApStartDHCPServer();
-
-  // print current IP address
-  Serial << F("IP Address :") << ip << "\r\n";
-
-  wsServer.registerConnectCallback(&onConnect);
-  wsServer.registerDataCallback(&onData);
-  wsServer.registerDisconnectCallback(&onDisconnect);
-  wsServer.begin();
-
-  // see if the card is present and can be initialized:
-  if (!SD.begin(chipSelect_SD)) {
-    Serial.println("Card failed, or not present");
-    return;
-  }
-  Serial.println("card initialized.");
-
-  exponent = FFT.Exponent(samples);
-
-  // Set accelerometers low pass filter at 60Hz
-  I2CwriteByte(MPU9250_ADDRESS,29,0x32);
-
-  // Configure accelerometers range
-  I2CwriteByte(MPU9250_ADDRESS,28,ACC_FULL_SCALE_4_G);
-
-  Timer23.setPeriodMs(5);             //Periodo di campionamento => frequenza di campionamento= 200Hz
-  Timer23.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt
-  Timer23.start();
-
-  // Store initial time
-  ti=millis();
-
-  data_base= (char**)malloc(10*sizeof(char*));
-}
-
-
-/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-void loop()
-{
-  //server in ascolto
-  wsServer.listen();
-
-  //attesa dati accelerometro
-  while (!intFlag);
-
-  intFlag=false;
-
-  // Read accelerometer
-  uint8_t Buf[14];
-  I2Cread(MPU9250_ADDRESS,0x3B,14,Buf);
-
-
-  // Accelerometer
-  vRealx[i] = -(Buf[0]<<8 | Buf[1]);
-  vImagx[i] = 0;
-  vRealy[i] = -(Buf[2]<<8 | Buf[3]);
-  vImagy[i] = 0;
-  vRealz[i] = Buf[4]<<8 | Buf[5];
-  vImagz[i] = 0;
-
-
-  if(i == samples-1)
-  {
-    for(int j=0; j<samples; j++)
-    {
-      vReala[j] = sqrt(sq(vRealx[j]) + sq(vRealy[j]) + sq(vRealz[j]));
-      vImaga[j] = 0;
-    }
-
-    //data x
-    PrintVectorjs(vRealx, vImagx, samples, SCL_TIME, x, ti);
-    FFT.Windowing(vRealx, samples, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
-    FFT.Compute(vRealx, vImagx, samples, exponent, FFT_FORWARD);
-    FFT.ComplexToMagnitude(vRealx, vImagx, samples);
-    PrintVectorjs(vRealx, vImagx, (samples/2), SCL_FREQUENCY, x, ti);
-      //double x = FFT.MajorPeak(vRealx, samples, sampling);
-
-    //data y
-    PrintVectorjs(vRealy, vImagy, samples, SCL_TIME, y, ti);
-    FFT.Windowing(vRealy, samples, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
-    FFT.Compute(vRealy, vImagy, samples, exponent, FFT_FORWARD);
-    FFT.ComplexToMagnitude(vRealy, vImagy, samples);
-    PrintVectorjs(vRealy, vImagy, (samples/2), SCL_FREQUENCY, y, ti);
-      //double y = FFT.MajorPeak(vRealy, samples, sampling);
-
-    //data z
-    PrintVectorjs(vRealz, vImagz, samples, SCL_TIME, z, ti);
-    FFT.Windowing(vRealz, samples, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
-    FFT.Compute(vRealz, vImagz, samples, exponent, FFT_FORWARD);
-    FFT.ComplexToMagnitude(vRealz, vImagz, samples);
-    PrintVectorjs(vRealz, vImagz, (samples/2), SCL_FREQUENCY, z, ti);
-      //double z = FFT.MajorPeak(vRealz, samples, sampling);
-
-    //data all
-    PrintVectorjs(vReala, vImaga, samples, SCL_TIME, a, ti);
-    FFT.Windowing(vReala, samples, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
-    FFT.Compute(vReala, vImaga, samples, exponent, FFT_FORWARD);
-    FFT.ComplexToMagnitude(vReala, vImaga, samples);
-    PrintVectorjs(vReala, vImaga, (samples/2), SCL_FREQUENCY, a, ti);
-      //double a = FFT.MajorPeak(vReala, samples, sampling);
-
-    Serial.println(data);
-    char data_server[data.length()+1];
-    data.toCharArray(data_server, data.length()+1);
-    data="";
-
-    //verifico se ci sono client connessi
-    if (wsServer.connectionCount() > 0)
-    {
-      wsServer.send(data_server, sizeof(data_server));
-      Serial.println("dati inviati");
-    }
-
-    data_base[j]= (char*)malloc(sizeof(data_server));
-    memmove (data_base[j], data_server, sizeof(data_server));
-
-    if( j == SIZE-1 )
-    {
-      getFileName(nome_file);
-      // open the file on SD
-      File dataFile = SD.open(nome_file+6, FILE_WRITE);
-
-      // if the file is available, write to it:
-      if (dataFile)
-      {
-        for(int i=0; i<SIZE; i++)
-        {
-          dataFile.println(data_base[i]);
-          free(data_base[i]);
-        }
-
-        dataFile.close();
-        // print to the serial port too:
-        Serial.println("scrittura ok");
-      }
-      // if the file isn't open, pop up an error:
-      else
-      {
-        Serial.println("error opening file");
-      }
-      j = 0;
-      free(data_base);
-      data_base= (char**)malloc(10 * sizeof(char*));
-    }
-    else j++;
-    i = 0;
-  }
-  else i++;
-}
-
-void PrintVectorjs(double *vDataR, double *vDataI, uint8_t bufferSize, uint8_t scaleType, int asseType, long int tempo)
-{
-    double abscissa;
-    char buffer[30];
-
-    switch (asseType)
-    {
-      case x:
-        if(scaleType == SCL_TIME){
-          data+= "{\"millis\":";
-          data+= itoa(millis()-tempo, buffer, 10);
-          memset(buffer, 0, 30);
-          data+= ",\"x\":[";
-        }
-        else  data+= ",";
-      break;
-      case y:
-        if(scaleType == SCL_TIME){
-          data+= "],\"y\":[";
-        }
-        else  data+= ",";
-      break;
-      case z:
-        if(scaleType == SCL_TIME){
-          data+= "],\"z\":[";
-        }
-        else  data+= ",";
-      break;
-      case a:
-        if(scaleType == SCL_TIME){
-          data+= "],\"all\":[";
-        }
-        else  data+= ",";
-      break;
-    }
-
-    switch (scaleType)
-    {
-      case SCL_INDEX:
-        data+= "{\"components\":[{\"real\": [";
-        for (int i = 0; i < bufferSize-1; i++)
-        {
-              sprintf(buffer, "%f", vDataR[i]);
-              data+= buffer;
-              memset(buffer, 0, 30);
-              data+= ",";
-        }
-        sprintf(buffer, "%f", vDataR[bufferSize-1]);
-        data+= buffer;
-        memset(buffer, 0, 30);
-        data+= "]},{\"imm\": [";
-        for (int i = 0; i < bufferSize-1; i++)
-        {
-              sprintf(buffer, "%f", vDataI[i]);
-              data+= buffer;
-              memset(buffer, 0, 30);
-              data+= ",";
-        }
-        sprintf(buffer, "%f", vDataI[bufferSize-1]);
-        data+= buffer;
-        memset(buffer, 0, 30);
-        data+= "]}]}";
-      break;
-      case SCL_TIME:
-        data+= "{\"signal\":[{\"time\": [";
-        for (int i = 0; i < bufferSize-1; i++)
-        {
-              abscissa = (i / sampling);
-              sprintf(buffer, "%f", abscissa);
-              data+= buffer;
-              memset(buffer, 0, 30);
-              data+= ",";
-        }
-        abscissa = (i / sampling);
-        sprintf(buffer, "%f", abscissa);
-        data+= buffer;
-        memset(buffer, 0, 30);
-        data+= "]},{\"real\": [";
-        for (int i = 0; i < bufferSize-1; i++)
-        {
-              sprintf(buffer, "%f", vDataR[i]);
-              data+= buffer;
-              memset(buffer, 0, 30);
-              data+= ",";
-        }
-        sprintf(buffer, "%f", vDataR[bufferSize-1]);
-        data+= buffer;
-        memset(buffer, 0, 30);
-        data+= "]}]}";
-      break;
-      case SCL_FREQUENCY:
-        data+= "{\"spectrum\":[{\"f\": [";
-        for (int i = 0; i < bufferSize-1; i++)
-        {
-              abscissa = ((i * sampling) / samples);
-              vDataI[i]= abscissa;
-              sprintf(buffer, "%f", abscissa);
-              data+= buffer;
-              memset(buffer, 0, 30);
-              data+= ",";
-        }
-        abscissa = ((i * sampling) / samples);               //STAMPA UN 1 IN PIU
-        vDataI[i]= abscissa;
-        sprintf(buffer, "%f", abscissa);
-        data+= buffer;
-        memset(buffer, 0, 30);
-        data+= "]},{\"e\": [";
-        for (int i = 0; i < bufferSize-1; i++)
-        {
-              sprintf(buffer, "%f", vDataR[i]);
-              data+= buffer;
-              memset(buffer, 0, 30);
-              data+= ",";
-        }
-        sprintf(buffer, "%f", vDataR[bufferSize-1]);
-        data+= buffer;
-        memset(buffer, 0, 30);
-        data+= "]}]}";
-        if(asseType == a){
-          data+= "]}";
-        }
-      break;
-    }
-}
-


Update SparkFun_MPL3115A2_Example.ino

Update SparkFun_MPL3115A2_Example.ino

Issues compiling example with the `../` in the header file's path. Removing.

--- firmware/examples/SparkFun_MPL3115A2_Example.ino
+++ firmware/examples/SparkFun_MPL3115A2_Example.ino
@@ -26,7 +26,7 @@
   please buy us a round!
   Distributed as-is; no warranty is given.
 *******************************************************************************/
-#include "../SparkFun_MPL3115A2/SparkFun_MPL3115A2.h"
+#include "SparkFun_MPL3115A2/SparkFun_MPL3115A2.h"
 float pascals = 0;
 float altf = 0;
 float baroTemp = 0;


Revert "Update BH1750FVI_Simple.ino"

Revert "Update BH1750FVI_Simple.ino"

This reverts commit 32fe05bbb80db305f6bcb70da35787dbdb53635b.

--- examples/BH1750FVI_Simple/BH1750FVI_Simple.ino
+++ examples/BH1750FVI_Simple/BH1750FVI_Simple.ino
@@ -1,260 +1,36 @@
+/*
+  This is a simple example to test the BH1750 Light sensor
+
+  Connect the sensor to a NodeMCU ESP8266:
+  VCC  <-> 3V3 [grey]
+  GND  <-> Gnd [purple]
+  SDA  <-> D2  [green]
+  SCL  <-> D1  [blue]
+  ADDR <-> RX  [yellow]
+ */

-
-// Includes: Wifi, MQTT, JSON
-#include<ESP8266WiFi.h>
-#include <PubSubClient.h>
-#include <ArduinoJson.h>
-
-// Includes: Sensors
 #include <Wire.h>
-#include "DHT.h"
 #include <BH1750FVI.h>

-// Defines: Wifi and MQTT
-#define mqtt_server "192.168.1.8"
-
-// Defines: Sensors
-#define DHTPIN 2  //D4
-#define DHTTYPE DHT11
-
-
-// Declarations: Wifi and MQTT
-char* ssid     = " xx ";
-const char* password = " xx ";
-WiFiClient espClient;
-PubSubClient client(espClient);
-
-// Declarations: JSON
-StaticJsonDocument<1024> jsonDoc;
-
-typedef struct keyAndValue_ {
-//   char key[100];
-//   char value[100];
-   String key;
-   String value;
-} keyAndValue_t;
-
-
-// Declarations: Sensors
-DHT DHT_dht(DHTPIN, DHTTYPE);
+// Settings
 uint8_t ADDRESSPIN = 13;
 BH1750FVI::eDeviceAddress_t DEVICEADDRESS = BH1750FVI::k_DevAddress_H;
 BH1750FVI::eDeviceMode_t DEVICEMODE = BH1750FVI::k_DevModeContHighRes;
+
+// Create the Lightsensor instance
 BH1750FVI LightSensor(ADDRESSPIN, DEVICEADDRESS, DEVICEMODE);

-
-
-void setup() {
+void setup()
+{
   Serial.begin(115200);
-  Serial.println("");
-  Serial.println("Starting connecting WiFi.");
-  delay(1000);
-  yield();
-  WiFi.begin(ssid, password);
-  yield();
-  while (WiFi.status() != WL_CONNECTED) {
-    yield();
-    delay(500);
-    Serial.print(".");
-  }
-  Serial.println("WiFi connected");
-  Serial.println("IP address: ");
-  Serial.println(WiFi.localIP());
-
-  client.setServer(mqtt_server, 1883);
-  client.setCallback(callback);
-
-  // setup sensors
-  DHT_dht.begin();
-  LightSensor.begin();
+  LightSensor.begin();
+  Serial.println("Running...");
 }

-void reconnect() {
-  // Loop until we're reconnected
-  while (!client.connected()) {
-    Serial.print("Attempting MQTT connection...");
-    // Attempt to connect
-    if (client.connect("sensorstation")) {
-      Serial.println("connected");
-      client.subscribe("sensorstation/command");
-    } else {
-      Serial.print("failed, rc=");
-      Serial.print(client.state());
-      Serial.println(" try again in 5 seconds");
-      // Wait 5 seconds before retrying
-      delay(5000);
-    }
-  }
-}
-
-void callback(char* topic, byte* payload, unsigned int length)
+void loop()
 {
-  Serial.println(" callback");
-}
-
-void loop() {
-  if (!client.connected()) {
-    reconnect();
-  }
-  client.loop();
-  delay(5000);
-  //MeasureDHT();
-  //MeasureFakeSensor(); //word deels overschreven door de volgende, return value van jsondoc maken en aan publish voeren?
-  MeasureBH1750FVI();  //en de dubbele komt niet aan bij nodered...
-  PublishValues();
-}
-
-void PublishValues() {
-  char buffer[1024];
-  serializeJson(jsonDoc, buffer);
-  Serial.println(buffer);
-  client.publish("sensorstation/json", buffer);
-  Serial.println("Published");
-}
-
-// DHT
-void MeasureDHTorg()
-{
-  /*
-    DHTPIN 2  //D4
-  */
-
-  float DHT_temp = 0;
-  float DHT_hum = 0;
-  float DHT_heatindex = 0;
-  char tempString[8];
-
-  DHT_temp = DHT_dht.readTemperature();
-  DHT_hum = DHT_dht.readHumidity();
-  DHT_heatindex = DHT_dht.computeHeatIndex(DHT_temp, DHT_hum, false);
-  //if (isnan(DHT_temp) || isnan(DHT_hum) || isnan(DHT_heatindex)) {
-  //  Serial.println("Failed to read from DHT sensor!");
-  //  return;
-  //}
-
-//todo, create root above sensor (buiten deze dht.
-  //add values to json
-  jsonDoc["sensor"] = "dht11";
-  jsonDoc["sensornumber"] = 1;
-  jsonDoc["data"]["temperature"] = dtostrf(DHT_temp, 5, 2, tempString);
-  jsonDoc["data"]["humidity"] = dtostrf(DHT_hum, 5, 2, tempString);
-  //jsonDoc["data"]["heatindex"] = dtostrf(DHT_heatindex, 5, 2, tempString);
-  //jsonDoc["data"]["heatindex"] = "1234";
-  Serial.print("DHT_temp     : "); Serial.print(DHT_temp); Serial.println(" C");
-  Serial.print("DHT_hum      : "); Serial.print(DHT_hum); Serial.println(" %");
-  Serial.print("DHT_heatindex: "); Serial.print(DHT_heatindex); Serial.println(" *C");
-  Serial.println("");
-}
-
-void AddData(String Sensor, uint8_t SensorNumber, keyAndValue_t SensorData[], uint8_t Count)
-{
-  /*
-  JsonObject measurement = jsonDoc.createNestedObject("measurement");
-  measurement["sensor"] = Sensor;
-  measurement["sensornumber"] = SensorNumber;
-
-  JsonObject measurement_data = measurement.createNestedObject("data");
-  //measurement_data["temperature"] = "24.10";
-  //measurement_data["humidity"] = "57.00";
-  for (int x = 0; x <= 1; x++) {
-    //for (int x = 0; x <= sizeof(SensorData)/sizeof(SensorData[0]); x++) {
-    measurement_data[SensorData[x].key] = SensorData[x].value;
-  }*/
-
-  jsonDoc["measurement"]["sensor"] = Sensor;
-  jsonDoc["measurement"]["sensornumber"] = SensorNumber;
-  for (int x = 0; x < Count; x++) {
-    jsonDoc["measurement"]["data"][String(SensorData[x].key)] = SensorData[x].value;
-  }
-
-  Serial.println("AddData:");
-  for (int x = 0; x < Count; x++) {
-    Serial.print(SensorData[x].key);
-    Serial.println(SensorData[x].value);
-  }
-  Serial.println("-------");
-}
-
-void AddDataold(String Sensor, uint8_t SensorNumber, String DataName, String DataValue)
-{
-  String Name(DataName);
-  jsonDoc["measurement"]["sensor"] = Sensor;
-  jsonDoc["measurement"]["sensornumber"] = SensorNumber;
-  jsonDoc["measurement"]["data"][Name] = DataValue;
-}
-
-// DHT
-void MeasureDHT()
-{
-  /*
-    DHTPIN 2  //D4
-  */
-
-  float DHT_temp = 0;
-  float DHT_hum = 0;
-  float DHT_heatindex = 0;
-  char tempString[8];
-
-  DHT_temp = DHT_dht.readTemperature();
-  DHT_hum = DHT_dht.readHumidity();
-  DHT_heatindex = DHT_dht.computeHeatIndex(DHT_temp, DHT_hum, false);
-  //if (isnan(DHT_temp) || isnan(DHT_hum) || isnan(DHT_heatindex)) {
-  //  Serial.println("Failed to read from DHT sensor!");
-  //  return;
-  //}
-
-//todo, create root above sensor (buiten deze dht.
-  //add values to json
-  jsonDoc["sensor"] = "dht11";
-  jsonDoc["sensornumber"] = 1;
-  jsonDoc["data"]["temperature"] = dtostrf(DHT_temp, 5, 2, tempString);
-  jsonDoc["data"]["humidity"] = dtostrf(DHT_hum, 5, 2, tempString);
-  //jsonDoc["data"]["heatindex"] = dtostrf(DHT_heatindex, 5, 2, tempString);
-  //jsonDoc["data"]["heatindex"] = "1234";
-  Serial.print("DHT_temp     : "); Serial.print(DHT_temp); Serial.println(" C");
-  Serial.print("DHT_hum      : "); Serial.print(DHT_hum); Serial.println(" %");
-  Serial.print("DHT_heatindex: "); Serial.print(DHT_heatindex); Serial.println(" *C");
-  Serial.println("");
-}
-
-void MeasureBH1750FVI()
-{
-  /*
-    VCC  <-> 3V3 [grey]
-    GND  <-> Gnd [purple]
-    SDA  <-> D2  [green]
-    SCL  <-> D1  [blue]
-    ADDR <-> RX  [yellow]
-  */
-
   uint16_t lux = LightSensor.GetLightIntensity();
   Serial.print("Light: ");
   Serial.println(lux);
-
-  keyAndValue_t SensorData[] = {
-    {"lux", String(lux)}
-  };
-
-  // Serial.println("SensorData:");
-  // for (int x = 0; x < sizeof(SensorData)/sizeof(SensorData[0]); x++) {
-  //   Serial.print(SensorData[x].key);
-  //   Serial.println(SensorData[x].value);
-  // }
-  //uint8_t Count = (sizeof(SensorData)/sizeof(SensorData[0]));    <---- werkt voor geen kloot
-  AddData("BH1750VI", 1, SensorData, 1);
+  delay(250);
 }
-
-// FakeSensor
-void MeasureFakeSensor()
-{
-  float FakeValA = 10.123;
-  float FakeValB = 20.123;
-
-  keyAndValue_t SensorData[] = {
-    {"FakeValA", String(FakeValA, 2)},
-    {"FakeValB", String(FakeValB, 3)}
-  };
-
-  //uint8_t Count = (sizeof(SensorData)/sizeof(SensorData[0]));
-  AddData("FakeSensor", 1, SensorData, 2);
-}


updated car control for microsecond steering and switch commands to float

--- arduino/car_control/src/main_control_nano/main_control_nano.ino
+++ arduino/car_control/src/main_control_nano/main_control_nano.ino
@@ -54,7 +54,7 @@
 };
 CmdMessenger commander = CmdMessenger(Serial,',',';','/');

-int _STEER_BIAS = 0; //set this to adjust steering
+float _STEER_BIAS = 0.0; //set this to adjust steering
 int _GOVERNER_F = 20; //cap the forward speed
 int _GOVERNER_R = -12;

@@ -66,8 +66,8 @@
 float steer_input = STEER_BASE;
 float throttle_input = THROTTLE_BASE;

-int throttle_pos;
-int steering_angle;
+float throttle_pos;
+float steering_angle;

 //make sure we have a transmitter so that we can safety stop the car
@@ -78,76 +78,36 @@
 volatile byte half_revolutions;
 unsigned int rpm;
 unsigned long timeold;
-
-
-//flags for emegency breaking
-bool emergency_breaking = true;
-
-//sonar
-unsigned int sonar_distance[SONAR_NUM];
-unsigned int pingTimer = 0;         // Where the ping distances are stored.
-NewPing sonar[SONAR_NUM] = {
-  NewPing(TRIGGER_PIN, ECHO_PIN_LEFT, MAX_DISTANCE),
-  NewPing(TRIGGER_PIN, ECHO_PIN_RIGHT, MAX_DISTANCE)
-};
-
-
+int rpm_decay;
+
+
+//emergency breaking
+bool emergency_breaking = false;

 //sets the steering angle between -45, 45 for full left /right respectively. set to zero for straight ahead
 void set_steer_angle(int angle) {
-  //dont set unless a delta has been acheived
-  if (abs(steering_angle - angle) / 2.0 < STEER_SENSITIVITY){
-    if (abs(angle) <= 2){
-      angle = 0;
-    }
-    else {
-      //not a big of change to change noise
-      return;
-    }
-
-    //if this value has already been set zero, no reason to set it again
-    if (steering_angle == 0) {
-      return;
-    }
-  }
-
   steering_angle = angle;
   commander.sendBinCmd(cmd_steer,steering_angle);
+

   //apply bias which accounts for physical issues, not model issues
   //we dont want our intented steer angle (0 for straight) to
   //reflect any issue in physical bias of the car
   angle = angle + _STEER_BIAS;

-  int map_angle = map(angle, -45, 45, 0, 180);
-  steering_servo.write(map_angle);
+  int map_angle_ms = int(map(angle, -45, 45, 1000, 2000));
+  steering_servo.write(map_angle_ms);
 }

 //when using the transmitter, map the steering to the TX output
 void set_steer_angle_manual(float sp) {
-  int map_angle = map(int(sp), STEER_MIN, STEER_MAX, -45, 45);
+  float map_angle = map(sp, STEER_MIN, STEER_MAX, -45.0, 45.0);
   set_steer_angle(map_angle);
 }

 //controls the acceleration/deccelration of the robot. -100 is full break to 100 full gas
-void set_throttle_position(int pos) {
-  //dont set unless a delta has been acheived
-  if (abs(throttle_pos - pos)/2.0 < THROTTLE_SENSITIVITY){
-    if (abs(pos) <= 5){
-      pos = 0;
-    }
-    else {
-      //not a big of change to change noise
-      return;
-    }
-
-    //if this value has already been set zero, no reason to set it again
-    if (throttle_pos == 0) {
-      return;
-    }
-  }
-
-
+
+void set_throttle_position(float pos) {
   //dont allow input past the limits, note we only limit reverse if the
   //standing throttle position is at zero. This allows for full breaking
   if (rpm < ROLLING_RPM){
@@ -160,7 +120,7 @@
   commander.sendBinCmd(cmd_throttle, throttle_pos);

   //note!!!!! the 1000 and 2000 here are the min and max PWM that the controller accepts
-  int map_throttle = map(pos, -100, 100, 1000, 2000);
+  int map_throttle = int(map(pos, -100, 100, 1000, 2000));

   throttle_servo.writeMicroseconds(map_throttle);
@@ -168,7 +128,25 @@

 //when using the transmitter, map the throttle to the TX output
 void set_throttle_position_manual(float sp) {
-  int map_throttle = map(int(sp), THROTTLE_MIN, THROTTLE_MAX, -100, 100);
+
+//  //dont set unless a delta has been acheived
+//  if (abs(throttle_pos - pos)/2.0 < THROTTLE_SENSITIVITY){
+//    if (abs(pos) <= 5){
+//      pos = 0;
+//    }
+//    else {
+//      //not a big of change to change noise
+//      return;
+//    }
+//
+//    //if this value has already been set zero, no reason to set it again
+//    if (throttle_pos == 0) {
+//      return;
+//    }
+//  }
+
+
+  float map_throttle = map(sp, THROTTLE_MIN, THROTTLE_MAX, -100, 100);
   set_throttle_position(map_throttle);
 }

@@ -318,9 +296,12 @@
   //look for commands
   commander.feedinSerialData();

-  //buffer the inputs, from the controller, they are noisy
-  steer_input = (steer_input + pulseIn(STEER_IN, HIGH, 25000)) / 2.0;
-  throttle_input = (throttle_input + pulseIn(THROTTLE_IN, HIGH, 25000)) / 2.0;
+  //buffer the inputs, from the controller, they are noisy
+//  steer_input = (steer_input * 2 + pulseIn(STEER_IN, HIGH, 250000)) / 3.0;
+//  throttle_input = (throttle_input * 2 + pulseIn(THROTTLE_IN, HIGH, 250000)) / 3.0;
+
+  steer_input = pulseIn(STEER_IN, HIGH, 250000);
+  throttle_input = pulseIn(THROTTLE_IN, HIGH, 250000);

   //if ever the transmitter is used, go into manual mode
   if (!manual_mode) {
@@ -335,6 +316,18 @@

   //output rpms
   write_rpms();
+
+  //decay rpms incase vehicle has stopped
+  if (rpm_decay >=2){
+    rpm_decay = int(rpm_decay/2);
+    if (rpm_decay < 2){
+      rpm = 0;
+      commander.sendBinCmd(cmd_rpm, rpm);
+     }
+  }
+
+
+

 }

@@ -383,30 +376,11 @@
 }

 void write_rpms(){
-  if (half_revolutions >= 6) {
+  if (half_revolutions >= 2) {
      rpm = 30 * 1000/(millis() - timeold) * half_revolutions;
+     rpm_decay = rpm;
      timeold = millis();
      half_revolutions = 0;
      commander.sendBinCmd(cmd_rpm, rpm);
   }
 }
-
-// void monitor_for_emergency_stop(){
-//   if ((sonar_distance[0] + sonar_distance[1])/2 <=  min(120, (40 + rpm/10)) &&
-//     rpm >= ROLLING_RPM) {
-//     commander.sendCmd(cmd_info, "OH SHIT");
-//     commander.sendCmd(cmd_info, String("  --RPM: ") + rpm);
-//     commander.sendCmd(cmd_info, String("  --TP: ") + throttle_pos);
-//     commander.sendCmd(cmd_info, String("  --LP: ") + sonar_distance[0]);
-//     commander.sendCmd(cmd_info, String("  --RP: ") + sonar_distance[1]);
-
-//     //emergency break
-//     set_throttle_position(-100);
-//     delay(3000);
-//     set_throttle_position(0);
-//     rpm = 0;
-
-//     //require arming
-//     // enter_arming_mode();
-//   }
-// }


start with m1 freq

start with m1 freq

--- vfobox.ino
+++ vfobox.ino
@@ -50,7 +50,7 @@
 const double bandEnd = 40000000; // End of Generator at 40 MHz --signal will be a bit flaky!
 const double bandInit = 7150000; // where to initially set the frequency for tetsting Part II

-double freq = bandInit ;  // this is a variable (changes) - set it to the beginning of the band
+double freq = 0 ;  // this is a variable (changes) - set it to the beginning of the band
 double freqDelta = 10000; // how much to change the frequency by, clicking the rotary encoder will change this.

 byte counter = 0;
@@ -72,9 +72,6 @@
   lcd.begin(16,2);
   lcd.setCursor(0,1); // This places a display on the LCD at turn on at the 2nd line
   lcd.print(" 5R8SV Sig Gen");
-  delay(250);
-  lcd.setCursor(0,1);
-  lcd.print("              ");

   // Set up DDS
   pinMode(FQ_UD, OUTPUT);
@@ -92,6 +89,14 @@
   // Set up memory buttons
   pinMode(M1Sw, INPUT_PULLUP);
   pinMode(M2Sw, INPUT_PULLUP);
+
+
+ // start on M1 freq
+  EEPROM.get(eeAddressStart,freq);
+  if(freq < bandStart || freq > bandEnd) {
+    freq = bandInit;
+    EEPROM.put(eeAddressStart,freq);
+  }

  // start up the DDS...
   pulseHigh(RESET);
@@ -100,6 +105,10 @@
   // start the oscillator...
   send_frequency(freq);
   display_frequency(freq);
+
+  delay(500);
+  lcd.setCursor(0,1);
+  lcd.print("              ");
 }

 void loop() {


NET_TH_METER works!

NET_TH_METER works!

--- net_th_meter/net_th_meter.ino
+++ net_th_meter/net_th_meter.ino
@@ -6,7 +6,9 @@
  * DHT22   - 1 unit,
  * DS18B20 - 3 units,
  * ENC28J60 based Ethernet controller.
- * Communicates using Modbus TCP.
+ *
+ * Communicates using Modbus TCP:
+ * Holding Registers (4x) 40001 - 40010
  *
  * (c) 2016, Mikhail Shiryaev
  */
@@ -22,13 +24,30 @@
 #define ONE_WIRE_PIN1 6 // the 2nd DS18B20 data
 #define ONE_WIRE_PIN2 7 // the 3rd DS18B20 data

-#define DHT_TYPE      DHT22 // DHT 22
-#define ONE_WIRE_CNT  3     // count of 1-wire connections
-#define TCP_PORT      502   // Modbus TCP default port
-#define RESPONSE_LEN  29    // length of Modbus TCP response
+#define DHT_TYPE        DHT22  // DHT 22
+#define ONE_WIRE_CNT    3      // count of 1-wire connections
+#define TCP_PORT        502    // Modbus TCP default port
+#define EMPTY_VAL       -100.0 // empty float value of measurement
+#define MODBUS_HDR_LEN  9      // length of Modbus TCP header
+
+//#define DEBUG
+
+#ifdef DEBUG
+ #define DEBUG_PRINT(val)       Serial.print(val)
+ #define DEBUG_PRINTHEX(val)    Serial.print(val, HEX)
+ #define DEBUG_PRINTLN(val)     Serial.println(val)
+ #define DEBUG_WRITETIME()      writeTime()
+#else
+ #define DEBUG_PRINT(val)
+ #define DEBUG_PRINTHEX(val)
+ #define DEBUG_PRINTLN(val)
+ #define DEBUG_WRITETIME()
+#endif

 // DHT instance
 DHT dht(DHT_PIN, DHT_TYPE);
+float dhtH = EMPTY_VAL;
+float dhtT = EMPTY_VAL;

 // 1-wire and DS instances
 OneWire oneWire0(ONE_WIRE_PIN0);
@@ -36,26 +55,32 @@
 OneWire oneWire2(ONE_WIRE_PIN2);
 OneWire oneWires[] = {oneWire0, oneWire1, oneWire2};
 DallasTemperature dsSensors[ONE_WIRE_CNT];
+float dsT[ONE_WIRE_CNT] = { EMPTY_VAL, EMPTY_VAL, EMPTY_VAL };

 // Ethernet
-byte mac[] = { 0xAB, 0xB6, 0xAA, 0x43, 0xA5, 0x9D };
+const byte mac[] = { 0xAB, 0xB6, 0xAA, 0x43, 0xA5, 0x9D };
 IPAddress ip(192, 168, 1, 8);
 EthernetServer server = EthernetServer(TCP_PORT);
 EthernetClient client;
 boolean clientConnected = false;
-byte response[RESPONSE_LEN] =
-  { 0x00, 0x00, 0x00, 0x00, 0x00, 0x17, 0x00, 0x03, 0x14, // bytes 0-9 - according to Modbus TCP specification
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,       // bytes 10-17 - holding registers 1-2, 3-4: dht_t, dht_h
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,       // bytes 18-25 - holding registers 5-6, 7-8: ds_t0, ds_t1
-    0x00, 0x00, 0x00, 0x00 };                             // bytes 26-29 - holding registers 9-10: ds_t2
+const byte modbusHeader[MODBUS_HDR_LEN] = {
+  0x00, 0x00, // Transaction identifier
+  0x00, 0x00, // Protocol identifier
+  0x00, 0x17, // Length
+  0x00,       // Unit identifier
+  0x03,       // Function code
+  0x14        // Byte count (20)
+};

 // Speed control
+#ifdef DEBUG
 unsigned long time;
+#endif

 // Initialize DHT sensor
 void initDHT() {
   dht.begin();
-  Serial.println("DHT sensor initialized");
+  DEBUG_PRINTLN("DHT sensor initialized");
 }

 // Initialize DS sensors
@@ -67,7 +92,7 @@
     if (dsSensors[i].getAddress(deviceAddress, 0))
       dsSensors[i].setResolution(deviceAddress, 12);
   }
-  Serial.println("DS sensors initialized");
+  DEBUG_PRINTLN("DS sensors initialized");
 }

 // Initialize ENC28J60 Ethernet controller
@@ -75,72 +100,74 @@
   Ethernet.begin(mac, ip);
   server.begin();

-  Serial.print("Ethernet initialized. IP: ");
-  Serial.println(Ethernet.localIP());
-}
-
+  DEBUG_PRINT("Ethernet initialized. IP: ");
+  Serial.print(Ethernet.localIP());
+  Serial.print(":");
+  Serial.println(TCP_PORT);
+}
+
+#ifdef DEBUG
 void writeTime() {
   Serial.print("Time elapsed = ");
   Serial.println(millis() - time);
 }
+#endif

 // Read data from DHT sensor
 void readDHT() {
-  writeTime();
-  Serial.println("Reading from DHT sensor");
-  float h = dht.readHumidity();
-  float t = dht.readTemperature(); // *C
-  Serial.println("Done");
-  writeTime();
-
-  if (isnan(h) || isnan(t)) {
-    Serial.println("Error reading from DHT sensor");
+  DEBUG_WRITETIME();
+  DEBUG_PRINTLN("Reading from DHT sensor");
+
+  dhtH = dht.readHumidity();
+  dhtT = dht.readTemperature(); // *C
+
+  DEBUG_WRITETIME();
+
+  if (isnan(dhtH) || isnan(dhtT)) {
+    dhtH = EMPTY_VAL;
+    dhtT = EMPTY_VAL;
+    DEBUG_PRINTLN("Error reading from DHT sensor");
   } else {
-    Serial.print("h = ");
-    Serial.print(h);
-    Serial.println(" %");
-    Serial.print("t = ");
-    Serial.print(t);
-    Serial.println(" *C");
-  }
-  writeTime();
-  Serial.println();
-}
-
-// Read data from DS sensors
-void readDS() {
-  writeTime();
-  Serial.println("Requesting DS sensors");
-  for (int i = 0; i < ONE_WIRE_CNT; i++) {
-    dsSensors[i].requestTemperatures();
-  }
-  Serial.println("Done");
-  writeTime();
-
-  for (int i=0; i < ONE_WIRE_CNT; i++) {
-    float t = dsSensors[i].getTempCByIndex(0);
-    Serial.print("t[");
-    Serial.print(i);
-    Serial.print("] = ");
-    Serial.print(t);
-    Serial.println(" *C");
-  }
-  writeTime();
-  Serial.println();
+    DEBUG_PRINT("h = ");
+    DEBUG_PRINTLN(dhtH);
+    DEBUG_PRINT("t = ");
+    DEBUG_PRINTLN(dhtT);
+  }
+
+  DEBUG_WRITETIME();
+  DEBUG_PRINTLN();
+}
+
+// Read data from DS sensor
+void readDS(int index) {
+  DEBUG_WRITETIME();
+  DEBUG_PRINT("Requesting DS sensor ");
+  DEBUG_PRINTLN(index);
+
+  dsSensors[index].requestTemperatures();
+
+  DEBUG_WRITETIME();
+
+  dsT[index] = dsSensors[index].getTempCByIndex(0);
+
+  DEBUG_PRINT("t = ");
+  DEBUG_PRINTLN(dsT[index]);
+  DEBUG_WRITETIME();
+  DEBUG_PRINTLN();
 }

 // Process Ethernet communication
 void communicate() {
-  writeTime();
+  DEBUG_WRITETIME();

   // manage connection
   if (clientConnected) {
     if (client.connected()) {
-      Serial.println("Client is still connected");
+      DEBUG_PRINTLN("Client is still connected");
     } else {
       client.stop();
       clientConnected = false;
-      Serial.println("Client has been disconnected");
+      DEBUG_PRINTLN("Client has been disconnected");
     }
   }

@@ -149,24 +176,25 @@
     client = server.available();
     if (client) {
       clientConnected = true;
-      Serial.println("New client is connected");
+      DEBUG_PRINTLN("New client is connected");
     } else {
-      Serial.println("Client is not connected");
+      DEBUG_PRINTLN("Client is not connected");
     }
   }

   // communicating
   if (clientConnected) {
     // wait for the request 00 00 00 00 00 06 01 03 00 00 00 0A
-    Serial.print("Receiving data: ");
+    DEBUG_PRINT("Receiving data: ");
     boolean sendResponse = false;
     while (client.available() > 0) {
       char c = client.read();
-      Serial.print(c, HEX);
-      Serial.print(" ");
+      DEBUG_PRINTHEX(c);
+      DEBUG_PRINT(" ");

       if (c == 0x0A) {
         sendResponse = true;
+        client.flush(); // clear input buffer
         break;
       }
     }
@@ -174,15 +202,18 @@

     // send response
     if (sendResponse) {
-      Serial.println("Sending response");
-      client.write(response, RESPONSE_LEN);
+      DEBUG_PRINTLN("Sending response");
+      client.write(modbusHeader, MODBUS_HDR_LEN);
+      client.write((byte*)&dhtH, 4);
+      client.write((byte*)&dhtT, 4);
+      client.write((byte*)&dsT, 12);
     } else {
-      Serial.println("Response not required");
-    }
-  }
-
-  writeTime();
-  Serial.println();
+      DEBUG_PRINTLN("Response not required");
+    }
+  }
+
+  DEBUG_WRITETIME();
+  DEBUG_PRINTLN();
 }

 void setup() {
@@ -191,21 +222,21 @@
   initDHT();
   initDS();
   initEthernet();
-  Serial.println();
+  DEBUG_PRINTLN();
 }

 void loop() {
-  time = millis();
-
-  // wait between measurements
+#ifdef DEBUG
+  time = millis();
   delay(500);
-
-  // read temperature and humidity from DHT sensors, takes around 270 milliseconds
-  readDHT();
-
-  // read temperatures from DS sensors, takes around 2370 milliseconds
-  readDS();
-
-  // Ethernet communication
-  communicate();
-}
+#endif
+
+  readDHT(); // around 270 ms
+  communicate();
+  readDS(0); // around 800 ms
+  communicate();
+  readDS(1); // around 800 ms
+  communicate();
+  readDS(2); // around 800 ms
+  communicate();
+}


Receive song signature

Receive song signature

--- ableton-midi-foot-controller.ino
+++ ableton-midi-foot-controller.ino
@@ -93,6 +93,7 @@
 const byte CONFIGURATION_FINISHED = 2;
 const byte CURRENT_PART = 3;
 const byte NEXT_PART = 4;
+const byte SONG_SIGNATURE = 5;

 const byte SONG_OFFSET = 10;

@@ -108,6 +109,15 @@
 boolean startedMidiNoteSending = false;

 boolean playing = false;
+byte numerator;
+byte denominator;
+byte bars;
+double fullDenominator;
+
+boolean nextPartScheduled = false;
+
+boolean repeat = false;
+elapsedMillis repeatEllapsed = 0;

 void OnNoteOn(byte channel, byte note, byte velocity) {
   digitalWrite(ledPin, HIGH);
@@ -146,6 +156,9 @@
       case NEXT_PART:
         handleNextPart(decoded + 4);
         break;
+      case SONG_SIGNATURE:
+        handleSongSignature(decoded + 4);
+        break;
     }
   }
 }
@@ -157,6 +170,32 @@
   lcd.clear();
   lcd.setCursor(0, 0);
   lcd.print(message);
+}
+
+void handleSongSignature(char* messageOriginal) {
+  if (mode != SONG_MODE) {
+    return;
+  }
+
+  char* message = (char*)calloc(strlen(messageOriginal) + 1, sizeof(char));
+  strcpy(message, messageOriginal);
+  char* strings;
+  strings = strtok(message, "|");
+  if (strings == NULL) {
+    return;
+  }
+
+  byte numeratorTemp = atoi(strings);
+
+  strings = strtok(NULL, "|");
+  if (strings == NULL) {
+    return;
+  }
+
+  byte denominatorTemp = atoi(strings);
+  numerator = numeratorTemp;
+  denominator = denominatorTemp;
+
 }

 void clearLine(byte line) {
@@ -247,6 +286,8 @@
     return CURRENT_PART;
   } else if (strcmp(strings, "NP") == 0) {
     return NEXT_PART;
+  } else if (strcmp(strings, "SS") == 0) {
+    return SONG_SIGNATURE;
   }
   return -1;
 }


Fixed apparently _long_ standing bug where short, continuous incoming nmea sentences could suck 100% of execution time.  Apparently it is a good idea to build a hardware testing harness and stress test devices :-)

--- device.ino
+++ device.ino
@@ -2012,7 +2012,8 @@

 void update_nmea()
 {
-  while(Serial2.available() && (int) nmea_read_buffer.length() < MAX_NMEA_BUFFER)
+  bool keep_going = true;
+  while(Serial2.available() && (int) nmea_read_buffer.length() < MAX_NMEA_BUFFER && keep_going == true)
   {
      int incoming_byte = Serial2.read();
      if(incoming_byte == '\n')
@@ -2023,6 +2024,7 @@
          parse_nmea_sentence();
        }
        nmea_read_buffer = "";
+       keep_going = false;
      }
      else if (incoming_byte == '\r')
      {
@@ -2042,7 +2044,8 @@

 void update_hsnmea()
 {
-  while(soft_serial.available() && (int) hsnmea_read_buffer.length() < MAX_NMEA_BUFFER)
+  bool keep_going = true;
+  while(soft_serial.available() && (int) hsnmea_read_buffer.length() < MAX_NMEA_BUFFER && keep_going == true)
   {
     int incoming_byte = soft_serial.read();
     if(incoming_byte == '\n')
@@ -2061,6 +2064,7 @@
       }
       #endif
       hsnmea_read_buffer = "";
+      keep_going = false;
     }
     else if (incoming_byte == '\r')
     {


Update garden.ino

Update garden.ino

totally revamped garden controller

--- garden.ino
+++ garden.ino
@@ -1,59 +1,65 @@
-#include <SPI.h>
-#include <SD.h>
-#include <TFT.h>  // Arduino LCD library

 #include <Wire.h>
 #include "RTClib.h"
-#include <DHT11.h>
+#include <math.h>
+int BH1750address = 0x23; //setting i2c address
+int light = 5;
+int ph_probe = A0;

-#define DHTPIN 11
-#define DHTTYPE DHT11
-#define sd_cs  12
-#define lcd_cs 6
-#define dc     7
-#define rst    8
-TFT screen = TFT(lcd_cs, dc, rst);
-
-DHT dht(DHTPIN, DHTTYPE);
-/*it's important that we set these variable per DHT sensor on our project*/
-
+int water_temp = 13
+byte buff[2];
 RTC_Millis rtc;

 void setup () {
     Serial.begin(57600);
     // following line sets the RTC to the date & time this sketch was compiled
     rtc.begin(DateTime(__DATE__, __TIME__));
-    screen.begin();
-    screen.background(0, 0, 0);
-    screen.stroke(100, 200, 255);
-    screen.println("welcome to the growbot");
-     delay(1000);
+    pinMode(light, OUTPUT);
+    Wire.begin();
+
 }

-void loop () {
-
-    DateTime now = rtc.now();
-    float h = dht.readHumidity();
-    float t = dht.readTemperature();
-    screen.text("temperature    humidity", 0,10);
-    screen.println("");
-    screen.print("");
-    screen.print(t);
-    screen.print("           ");
-    screen.println(h);
-    screen.print(now.year(), DEC);
-    screen.print('/');
-    screen.print(now.month(), DEC);
-    screen.print('/');
-    screen.print(now.day(), DEC);
-    screen.print(' ');
-    screen.print(now.hour(), DEC);
-    screen.print(':');
-    screen.print(now.minute(), DEC);
-    screen.print(':');
-    screen.print(now.second(), DEC);
-    screen.println();
-    delay(3000);
-    screen.background(0, 0, 0);
+void loop()
+{
+     digitalWrite(light, LOW); //turn the light on
+
+}

+
+void report_lux()
+{
+  int i;
+  uint16_t val=0;
+  BH1750_Init(BH1750address);
+  delay(200);
+
+  if(2==BH1750_Read(BH1750address))
+  {
+    val=((buff[0]<<8)|buff[1])/1.2;
+    Serial.print(val,DEC);
+    Serial.println("[lx]");
+  }
+  delay(150);
 }
+
+
+int BH1750_Read(int address) //
+{
+  int i=0;
+  Wire.beginTransmission(address);
+  Wire.requestFrom(address, 2);
+  while(Wire.available()) //
+  {
+    buff[i] = Wire.read();  // receive one byte
+    i++;
+  }
+  Wire.endTransmission();
+  return i;
+}
+
+void BH1750_Init(int address)
+{
+  Wire.beginTransmission(address);
+  Wire.write(0x10);//1lx reolution 120ms
+  Wire.endTransmission();
+}


Correção da leitura do ROLL (sobrescrevendo pino do motor).

--- quad/quad.ino
+++ quad/quad.ino
@@ -23,8 +23,9 @@
 #endif

 #ifdef DEBUG
-  long tmCheckpoint; // Marca o tempo no checkpoint
-  long tmInterval;   // Intervalo entre última medição e o checkpoint
+  long tmCheckpoint;   // Marca o tempo no checkpoint
+  long tmInterval;     // Intervalo entre última medição e o checkpoint
+  int countToSend = 0; // Controla o intervalo de envio das informações
 #endif

 /* Indicação de atividade do processador */
@@ -61,7 +62,7 @@
 unsigned long channels[6];

 /* Valores normalizados dos canais */
-long rcThrottle, rcYaw, rcPitch, rcRoll, rcOnOff, rcDimmer;
+double rcThrottle, rcYaw, rcPitch, rcRoll, rcOnOff, rcDimmer;

 /**************************************
  * Giroscópio e Acelerômetro: MPU6050 *
@@ -81,7 +82,7 @@
 Quaternion q;        // [w, x, y, z]         Container do quaternion
 VectorFloat gravity; // [x, y, z]            Vetor de gravidade
 float ypr[3]; // [yaw, pitch, roll]   Container do yaw/pitch/roll e do vetor de gravidade
-float ypr_degree[3]; // [yaw, pitch, roll]   Container do yaw/pitch/roll e do vetor de gravidade em graus/segundo
+double ypr_degree[3]; // [yaw, pitch, roll]   Container do yaw/pitch/roll e do vetor de gravidade em graus/segundo

 const int DMP_YAW = 0;
 const int DMP_PITCH = 1;
@@ -120,14 +121,14 @@
 } pid_params;

 /* Variáveis de saída do PID para a taxa de rotação */
-float pitch_rate_output;
-float roll_rate_output;
-float yaw_rate_output;
+double pitch_rate_output;
+double roll_rate_output;
+double yaw_rate_output;

 /* Variáveis de saída do PID para a estabilização */
-float pitch_stab_output;
-float roll_stab_output;
-float yaw_stab_output;
+double pitch_stab_output;
+double roll_stab_output;
+double yaw_stab_output;

 /* PIDs para a taxa de rotação. Entrada: taxa de rotação do giroscópio. Objetivo: Taxa de giro proporcional ao erro. Saída: Potência para o motor. */
 /*                         ENTRADA                         SAÍDA                  OBJETIVO        P   D  I  DIREÇÃO */
@@ -136,10 +137,10 @@
 //PID pid_yaw_rate   (/* taxa de giro */, &yaw_rate_output, &yaw_stab_output, 1, 2, 3, DIRECT);

 /* PIDs para a taxa de estabilização. Entrada: posição do quadricóptero através do MPU. Objetivo: Posição indicada através do controle. Saída: Taxa de giro proporcional ao erro. */
-/*                         ENTRADA                         SAÍDA                  OBJETIVO        P   D  I  DIREÇÃO */
-PID pid_pitch_stab ((double *)&ypr[DMP_PITCH], (double *)&pitch_stab_output, (double *)&rcPitch, 0.7, 0, 1, DIRECT);
-PID pid_roll_stab  ((double *)&ypr[DMP_ROLL],  (double *)&roll_stab_output,  (double *)&rcRoll,  0.7, 0, 1, DIRECT);
-PID pid_yaw_stab   ((double *)&ypr[DMP_YAW],   (double *)&yaw_stab_output,   (double *)&rcYaw,   0.7, 0, 1, DIRECT);
+/*                        ENTRADA                 SAÍDA          OBJETIVO  P  I  D  DIREÇÃO */
+PID pid_pitch_stab (&ypr_degree[DMP_PITCH], &pitch_stab_output, &rcPitch, 10, 4, 0, DIRECT);
+PID pid_roll_stab  (&ypr_degree[DMP_ROLL],  &roll_stab_output,  &rcRoll,  10, 4, 0, DIRECT);
+PID pid_yaw_stab   (&ypr_degree[DMP_YAW],   &yaw_stab_output,   &rcYaw,   10, 4, 0, DIRECT);
 /* Fim do PID */

 /*************************
@@ -147,10 +148,10 @@
  *************************/

 /* Canais de cada motor */
-const int MOTOR_PIN_FL = 8; /* To-do test this pin */
-const int MOTOR_PIN_FR = 9;
-const int MOTOR_PIN_BL = 10; /* To-do test this pin */
-const int MOTOR_PIN_BR = 11; /* To-do test this pin */
+const int MOTOR_PIN_FL = 9; /* To-do test this pin */
+const int MOTOR_PIN_FR = 10;
+const int MOTOR_PIN_BL = 11; /* To-do test this pin */
+const int MOTOR_PIN_BR = 12; /* To-do test this pin */

 /* Entidades que representam os motores. Responsáveis por acionar os ESCs realizando um PPM entre 1ms e 2ms. */
 Servo motorFL;
@@ -175,8 +176,8 @@
   pinMode(CH1, INPUT);
   pinMode(CH2, INPUT);
   pinMode(CH3, INPUT);
+  pinMode(CH5, INPUT);
   pinMode(CH4, INPUT);
-  pinMode(CH5, INPUT);
   pinMode(CH6, INPUT);

   /* Bind dos canais de saída dos motores (ESCs) */
@@ -248,17 +249,20 @@
   static float yaw_target = 0;

   /* Se a programação do DMP falhou, não faz nada */
+  Serial.println("!dmpReady");
   if (!dmpReady) {
     return;
   }

+  Serial.println("readOrientation");
   readOrientation();

+  Serial.println("readRC");
   readRC();

   /* Voe Forest, Voe! */
   if(rcThrottle > MIN_RC_THROTTLE + 100) {  // Throttle raised, turn on stablisation.
-
+    Serial.println("PID");
     pid_pitch_stab.Compute();
     pid_roll_stab.Compute();
     pid_yaw_stab.Compute();
@@ -301,6 +305,7 @@
     motors[MOTOR_BR] = rcThrottle - roll_stab_output - pitch_stab_output - yaw_stab_output;

   } else {
+    Serial.println("else");
     /* Motores desligados */
     motors[MOTOR_FL] = motors[MOTOR_FR] = motors[MOTOR_BL] = motors[MOTOR_BR] = 1000;

@@ -314,10 +319,13 @@
     // }
   }

+  Serial.println("writeMotor");
   writeMotor();

+  Serial.println("telemetry");
   D(telemetry());

+  Serial.println("blink");
   /* Pisca a led para indicar atividade */
   blinkState = !blinkState;
   digitalWrite(LED_PIN, blinkState);
@@ -325,22 +333,22 @@

 /* Efetua a leitura dos canais dos controles. */
 void readRC() {
-  channels[0] = pulseIn(CH1, HIGH);
-  channels[1] = pulseIn(CH2, HIGH);
-  channels[2] = pulseIn(CH3, HIGH);
-  channels[3] = pulseIn(CH4, HIGH);
-  channels[4] = pulseIn(CH5, HIGH);
-  channels[5] = pulseIn(CH6, HIGH);
+  channels[0] = pulseIn(CH1, HIGH); /* Roll (horizontal da direita) */
+  channels[1] = pulseIn(CH2, HIGH); /* Pitch (vertical da direita) */
+  channels[2] = pulseIn(CH3, HIGH); /* Throttle (vertical da esquerda) */
+  channels[3] = pulseIn(CH4, HIGH); /* Yaw (horizontal da esquerda */
+  channels[4] = pulseIn(CH5, HIGH); /* ON/OFF */
+  channels[5] = pulseIn(CH6, HIGH); /* Dimmer */

   normalizeRC();
 }

 /* Normaliza os valores do controle para ranges pré definidos. */
 void normalizeRC() {
+  rcRoll     = map(channels[0], MIN_RC_ROLL, MAX_RC_ROLL, -45, 45);
+  rcPitch    = map(channels[1], MIN_RC_PITCH, MAX_RC_PITCH, 45, -45);
   rcThrottle = channels[2];
   rcYaw      = map(channels[3], MIN_RC_YAW, MAX_RC_YAW, -150, 150);
-  rcPitch    = map(channels[1], MIN_RC_PITCH, MAX_RC_PITCH, 45, -45);
-  rcRoll     = map(channels[0], MIN_RC_ROLL, MAX_RC_ROLL, -45, 45);
   rcOnOff    = map(channels[4], MIN_RC_ON_OFF, MAX_RC_ON_OFF, 0, 100);
   rcDimmer   = map(channels[5], MIN_RC_DIMMER, MAX_RC_DIMMER, 0, 1000);
 }
@@ -436,28 +444,32 @@
   tmCheckpoint = micros();

   String tmValues;
-  tmValues += padding("RCT=" + String(rcThrottle), 8) + ";";
-  tmValues += padding("RCY=" + String(rcYaw), 8) + ";";
-  tmValues += padding("RCP=" + String(rcPitch), 8) + ";";
-  tmValues += padding("RCR=" + String(rcRoll), 8) + ";";
-  tmValues += padding("RCO=" + String(rcOnOff), 8) + ";";
-  tmValues += padding("RCD=" + String(rcDimmer), 8) + ";";
-  tmValues += padding("DMP=" + String(ypr_degree[DMP_PITCH]), 10) + ";";
-  tmValues += padding("DMR=" + String(ypr_degree[DMP_ROLL]), 10) + ";";
-  tmValues += padding("DMY=" + String(ypr_degree[DMP_YAW]), 10) + ";";
-  tmValues += padding("PIP=" + String(pitch_stab_output), 7) + ";";
-  tmValues += padding("PIR=" + String(roll_stab_output), 7) + ";";
-  tmValues += padding("PIY=" + String(yaw_stab_output), 7) + ";";
-  tmValues += padding("MFL=" + String(motors[MOTOR_FL]), 8) + ";";
-  tmValues += padding("MFR=" + String(motors[MOTOR_FR]), 8) + ";";
-  tmValues += padding("MBL=" + String(motors[MOTOR_BL]), 8) + ";";
-  tmValues += padding("MBR=" + String(motors[MOTOR_BR]), 8) + ";";
-  tmValues += padding("INT=" + String(tmInterval), 10) + ";";
-  // for (int i=0; i < 6; i++) {
-  //  tmValues += padding(String(channels[i]), 8) + ";";
-  // }
-
-  Serial.println(tmValues);
+  tmValues += padding("RCT=" + String(int(rcThrottle)), 8) + ";";
+  tmValues += padding("RCY=" + String(int(rcYaw)), 8) + ";";
+  tmValues += padding("RCP=" + String(int(rcPitch)), 8) + ";";
+  tmValues += padding("RCR=" + String(int(rcRoll)), 8) + ";";
+  tmValues += padding("RCO=" + String(int(rcOnOff)), 8) + ";";
+  tmValues += padding("RCD=" + String(int(rcDimmer)), 8) + ";";
+  tmValues += padding("DMP=" + String(int(ypr_degree[DMP_PITCH])), 10) + ";";
+  tmValues += padding("DMR=" + String(int(ypr_degree[DMP_ROLL])), 10) + ";";
+  tmValues += padding("DMY=" + String(int(ypr_degree[DMP_YAW])), 10) + ";";
+  tmValues += padding("PIP=" + String(int(pitch_stab_output)), 8) + ";";
+  tmValues += padding("PIR=" + String(int(roll_stab_output)), 8) + ";";
+  tmValues += padding("PIY=" + String(int(yaw_stab_output)), 8) + ";";
+  tmValues += padding("MFL=" + String(int(motors[MOTOR_FL])), 8) + ";";
+  tmValues += padding("MFR=" + String(int(motors[MOTOR_FR])), 8) + ";";
+  tmValues += padding("MBL=" + String(int(motors[MOTOR_BL])), 8) + ";";
+  tmValues += padding("MBR=" + String(int(motors[MOTOR_BR])), 8) + ";";
+  tmValues += padding("INT=" + String(int(tmInterval)), 10) + ";";
+  for (int i=0; i < 6; i++) {
+   tmValues += padding(String(channels[i]), 8) + ";";
+  }
+
+  countToSend++;
+  if (countToSend > 4) {
+    Serial.println(tmValues);
+    countToSend = 0;
+  }
 }

 String padding(String text, int size){


Finished code and added acceleration sensor.

--- CreatedCode/Arduino/LevelerSensor/LevelerSensor.ino
+++ CreatedCode/Arduino/LevelerSensor/LevelerSensor.ino
@@ -242,27 +242,28 @@
             Serial.print("\tCount: ");
             Serial.println(count);

-/*
+
             // display real acceleration, adjusted to remove gravity
             mpu.dmpGetQuaternion(&q, fifoBuffer);
             mpu.dmpGetAccel(&aa, fifoBuffer);
             mpu.dmpGetGravity(&gravity, &q);
             mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
-            Serial.print("areal\t");
-            Serial.print(aaReal.x);
-            Serial.print("\t");
-            Serial.print(aaReal.y);
-            Serial.print("\t");
-            Serial.print(aaReal.z);
-            Serial.print("\t");
-
-            Serial.print("Count: ");
-            Serial.println(count);
+//            Serial.print("areal\t");
+//            Serial.print(aaReal.x);
+//            Serial.print("\t");
+//            Serial.print(aaReal.y);
+//            Serial.print("\t");
+//            Serial.print(aaReal.z);
+//            Serial.print("\t");

         // Set acceleration values here
-        dx = aaReal.x - tempx;
-        dy = ay - tempy;
-        dz = az - tempz;
+        accelX = aaReal.x;
+        accelY = aaReal.y;
+        accelZ = aaReal.z;
+        dx = abs(accelX) - abs(tempx);
+        dy = abs(accelY) - abs(tempy);
+        dz = abs(accelZ) - abs(tempz);
+
         dx = (dx/10);
         int modx = dx%10;
         dx = dx-modx;
@@ -273,10 +274,10 @@
         int modz = dz%10;
         dz = dz-modz;

-        tempx = ax;
-        tempy = ay;
-        tempz = az;
- */
+        tempx = accelX;
+        tempy = accelY;
+        tempz = accelZ;
+
         if(count < calibrateCount) {
           count++;
           if(count%100 < 50) {
@@ -298,9 +299,11 @@
           digitalWrite(level, LOW);
           setRef = true;
         } else {
-          //Test to see if moving here
-
-          if(abs(abs(xDeg)-abs(refX)) < 8 && abs(abs(zDeg)-abs(refZ)) < 8) {
+          if(abs(dx) > 20 || abs(dy) > 20 || abs(dz) > 20) {
+            digitalWrite(tilted, LOW);
+            digitalWrite(moving, HIGH);
+            digitalWrite(level, LOW);
+          } else if(abs(abs(zDeg)-abs(refZ)) < 8) {       //abs(abs(xDeg)-abs(refX)) < 8 &&
             digitalWrite(tilted, LOW);
             digitalWrite(moving, LOW);
             digitalWrite(level, HIGH);
@@ -309,37 +312,15 @@
             digitalWrite(moving, LOW);
             digitalWrite(level, LOW);
           }
+          /*
+          else if(abs(abs(xDeg)-abs(refX)) > 15) {
+            digitalWrite(tilted, HIGH);
+            digitalWrite(moving, LOW);
+            digitalWrite(level, LOW);
+          }
+           */
         }
-
-            /*
-             // display real acceleration, adjusted to remove gravity
-            mpu.dmpGetQuaternion(&q, fifoBuffer);
-            mpu.dmpGetAccel(&aa, fifoBuffer);
-            mpu.dmpGetGravity(&gravity, &q);
-            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
-            Serial.print("areal\t");
-            Serial.print(aaReal.x);
-            Serial.print("\t");
-            Serial.print(aaReal.y);
-            Serial.print("\t");
-            Serial.println(aaReal.z);
-            */
-
-            /*
-            // display initial world-frame acceleration, adjusted to remove gravity
-            // and rotated based on known orientation from quaternion
-            mpu.dmpGetQuaternion(&q, fifoBuffer);
-            mpu.dmpGetAccel(&aa, fifoBuffer);
-            mpu.dmpGetGravity(&gravity, &q);
-            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
-            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
-            Serial.print("aworld\t");
-            Serial.print(aaWorld.x);
-            Serial.print("\t");
-            Serial.print(aaWorld.y);
-            Serial.print("\t");
-            Serial.println(aaWorld.z);
-            */
+

         // blink LED to indicate activity
         blinkState = !blinkState;


+added new version power_router.ino (may inedit sa pagcompute ng voltage)

--- power_router/power_router.ino
+++ power_router/power_router.ino
@@ -173,9 +173,10 @@
 	Serial.println(F("Read voltage: "));

         digitalWrite(sv, HIGH);
-	delay(500);
+	delay(10000);
         voltage = (analogRead(A0) * (12.5 / 1023.0)); //mapped with 12.5V as maximum
-	Serial.println(voltage);
+	//voltage = ((((analogRead(A0) * 3.3)/1023)-0.1973)/0.1844);
+        Serial.println(voltage);
 	digitalWrite(sv, LOW);

         return;


Fix strip ordering.

Fix strip ordering.

--- usb-to-octows2811/usb-to-octows2811.ino
+++ usb-to-octows2811/usb-to-octows2811.ino
@@ -63,14 +63,14 @@
   digitalWriteFast(STATUS_LED, HIGH);

   Serial.begin(115200);
+  FastLED.addLeds<OCTOWS2811>(leds, NUM_LEDS_STRIP_D);
+  FastLED.addLeds<OCTOWS2811>(leds, NUM_LEDS_STRIP_C);
+  FastLED.addLeds<OCTOWS2811>(leds, NUM_LEDS_STRIP_B);
   FastLED.addLeds<OCTOWS2811>(leds, NUM_LEDS_STRIP_A);
+  FastLED.addLeds<OCTOWS2811>(leds, NUM_LEDS_STRIP_D);
+  FastLED.addLeds<OCTOWS2811>(leds, NUM_LEDS_STRIP_C);
   FastLED.addLeds<OCTOWS2811>(leds, NUM_LEDS_STRIP_B);
-  FastLED.addLeds<OCTOWS2811>(leds, NUM_LEDS_STRIP_C);
-  FastLED.addLeds<OCTOWS2811>(leds, NUM_LEDS_STRIP_D);
   FastLED.addLeds<OCTOWS2811>(leds, NUM_LEDS_STRIP_A);
-  FastLED.addLeds<OCTOWS2811>(leds, NUM_LEDS_STRIP_B);
-  FastLED.addLeds<OCTOWS2811>(leds, NUM_LEDS_STRIP_C);
-  FastLED.addLeds<OCTOWS2811>(leds, NUM_LEDS_STRIP_D);

   FastLED.setCorrection(TypicalSMD5050);
   FastLED.setTemperature(Tungsten100W);


Delete MPU_GameController_Blog.ino

Delete MPU_GameController_Blog.ino

--- MPU_GameController_Blog/MPU_GameController_Blog.ino
+++ MPU_GameController_Blog/MPU_GameController_Blog.ino
@@ -1,179 +0,0 @@
-#define INVERT_X   //invert pitch
-#define INVERT_Y   //invert roll
-
-//#define DEBUG          //uncomment this for testing,
-                         //comment it before making joystick
-
-
-#include "UnoJoy.h"
-#include <Wire.h>
-
-#define XSensitivity 3.0
-#define YSensitivity 3.0
-
-
-/* IMU Data */
-double accX, accY, accZ;
-double gyroX, gyroY, gyroZ;
-double tempRaw;
-double dt;
-
-double compAngleX, compAngleY; // Calculated angle using a complementary filter
-
-uint32_t timer;
-uint8_t i2cData[14]; // Buffer for I2C data
-
-
-void setup() {
-
-#ifdef DEBUG
-  Serial.begin(38400);
-  Serial.println("Ready");
-  Serial.print("compAngleX");  Serial.print('\t');
-  Serial.print("compAngleY");  Serial.print('\t');
-  Serial.print("leftStickX");  Serial.print('\t');
-  Serial.print("leftStickY");  Serial.print('\t');
-  Serial.print("rightStickX");  Serial.print('\t');
-  Serial.print("rightStickY");  Serial.print('\t');
-  Serial.println();
-  delay(4000);
-#endif
-
-  InitializeGPIO();
-  InitializeMpu();
-  delay(100); // Wait for sensor to stabilize
-
-  UpdateReadings();     //Updates accel/gyro readings
-  SetInitialValues();   //Set inital roll and pitch values
-
-  setupUnoJoy();
-  timer = micros();
-}
-
-void loop() {
-
-  UpdateReadings();
-  dt = (double)(micros() - timer) / 1000000; // Calculate delta time
-  timer = micros();
-
-  ComputeAngles();
-
-  dataForController_t controllerData = getControllerData(compAngleX * XSensitivity, compAngleY * YSensitivity);
-
-#ifdef DEBUG
-  Serial.print(compAngleX);  Serial.print('\t');
-  Serial.print(compAngleY);  Serial.print('\t');
-  Serial.print(controllerData.leftStickX);  Serial.print('\t');
-  Serial.print(controllerData.leftStickY);  Serial.print('\t');
-  Serial.print(controllerData.rightStickX);  Serial.print('\t');
-  Serial.print(controllerData.rightStickY);  Serial.print('\t');
-  Serial.println();
-#else
-  setControllerData(controllerData);
-#endif
-
-  delay(2);
-}
-
-void InitializeGPIO()
-{
-  for (int i = 2; i <= 5; i++)
-  {
-    pinMode(i, INPUT);
-    digitalWrite(i, HIGH);
-  }
-}
-
-
-void InitializeMpu()
-{
-  Wire.begin();
-  Wire.setClock(400000UL);
-
-  i2cData[0] = 7; // Set the sample rate to 1000Hz - 8kHz/(7+1) = 1000Hz
-  i2cData[1] = 0x00; // Disable FSYNC and set 260 Hz Acc filtering, 256 Hz Gyro filtering, 8 KHz sampling
-  i2cData[2] = 0x00; // Set Gyro Full Scale Range to ±250deg/s
-  i2cData[3] = 0x00; // Set Accelerometer Full Scale Range to ±2g
-  while (i2cWrite(0x19, i2cData, 4, false)); // Write to all four registers at once
-  while (i2cWrite(0x6B, 0x01, true)); // PLL with X axis gyroscope reference and disable sleep mode
-
-  while (i2cRead(0x75, i2cData, 1));
-  if (i2cData[0] != 0x68)
-  { // Read "WHO_AM_I" register
-    Serial.print(F("Error reading sensor"));
-    while (1);
-  }
-}
-
-
-void UpdateReadings()
-{
-  while (i2cRead(0x3B, i2cData, 14));
-  accX = ((i2cData[0] << 8) | i2cData[1]);
-  accY = ((i2cData[2] << 8) | i2cData[3]);
-  accZ = ((i2cData[4] << 8) | i2cData[5]);
-  tempRaw = (i2cData[6] << 8) | i2cData[7];
-  gyroX = (i2cData[8] << 8) | i2cData[9];
-  gyroY = (i2cData[10] << 8) | i2cData[11];
-  gyroZ = (i2cData[12] << 8) | i2cData[13];
-
-}
-
-
-void SetInitialValues()
-{
-  // Source: http://www.freescale.com/files/sensors/doc/app_note/AN3461.pdf eq. 25 and eq. 26
-  // atan2 outputs the value of -π to π (radians) - see http://en.wikipedia.org/wiki/Atan2
-  double roll  = atan2(accY, accZ) * RAD_TO_DEG;
-  double pitch = atan(-accX / sqrt(accY * accY + accZ * accZ)) * RAD_TO_DEG;
-  compAngleX = roll;
-  compAngleY = pitch;
-}
-
-
-void ComputeAngles()
-{
-  double roll  = atan2(accY, accZ) * RAD_TO_DEG;
-  double pitch = atan(-accX / sqrt(accY * accY + accZ * accZ)) * RAD_TO_DEG;
-
-  double gyroXrate = gyroX / 131.0; // Convert to deg/s
-  double gyroYrate = gyroY / 131.0; // Convert to deg/s
-
-  compAngleX = 0.98 * (compAngleX + gyroXrate * dt) + 0.02 * roll; // Calculate the angle using a Complimentary filter
-  compAngleY = 0.98 * (compAngleY + gyroYrate * dt) + 0.02 * pitch;
-}
-
-
-dataForController_t getControllerData(double _roll, double _pitch) {
-
-#ifdef INVERT_X
-  _pitch = -_pitch;
-#endif
-#ifdef INVERT_Y
-  _roll = -_roll;
-#endif
-
-  //Restrict roll and pitch to +-90
-  if (_roll > 90 || _roll < -90)
-    _roll = 90 * _roll / abs(_roll);
-
-  if (_pitch > 90 || _pitch < -90)
-    _pitch = 90 * _pitch / abs(_pitch);
-
-
-  //Get new instance with default values of buttons and sticks
-  dataForController_t controllerData = getBlankDataForController();
-
-  controllerData.leftStickX = (int)(_pitch * 1.422 + 128);
-  controllerData.leftStickY =  (int)(_roll * 1.422 + 128);
-
-  //You can use these and many other buttons also
-  controllerData.triangleOn = !digitalRead(2);
-  controllerData.circleOn = !digitalRead(3);
-  controllerData.squareOn = !digitalRead(4);
-  controllerData.crossOn = !digitalRead(5);
-
-  return controllerData;
-}
-
-


Robot now avoids obstacle most of the time

--- iso/carl_breadboard/carl_breadboard.ino
+++ iso/carl_breadboard/carl_breadboard.ino
@@ -86,16 +86,18 @@
 		} while (GETULTRA && distside < 20 && distside > 0);
 		do {
 			motor_SetOutputs(0,255,0,0);
-			delay(100);
+			delay(75);
 			FORWARD
 			delay(75);
 		} while (GETULTRA && (distside < 1 || distside > 19 ));
 		do {
+			motor_SetOutputs(0,255,0,0);
+			delay(100);
 			FORWARD
-			delay(50);
+			delay(75);
 		} while (!(digitalRead(LINEPIN1) || digitalRead(LINEPIN2)));
 		motor_SetOutputs(0,0,0,0);
-		delay(2000);
+		// delay(2000);
 		pright=255;
 		pleft=0;
 	}


updated parallel out 2

updated parallel out 2

--- proj/parallel_out_test_2/parallel_out_test_2.ino
+++ proj/parallel_out_test_2/parallel_out_test_2.ino
@@ -17,8 +17,6 @@
 void setup() {
   LEDS.addLeds<WS2811_PORTD, NUM_STRIPS>(leds, NUM_LED);
   LEDS.setBrightness(32);
-
-  //LEDS.setMaxPowerInMilliWatts(24000);
 }

 void loop() {
@@ -29,6 +27,13 @@

   update_RainbowBlack_p();
   theater_chase();
+
+  static uint8_t hue = 0;
+  for (int i = 0; i < NUM_STRIPS; i++) {
+    for (int j = 0; j < NUM_LED; j++) {
+      leds[(i * NUM_LED) + j] = CHSV((32 * i) + hue + j, 192, 255);
+    }
+  }

   // Set the first n leds on each strip to show which strip it is
   for (int i = 0; i < NUM_STRIPS; i++) {
@@ -48,7 +53,7 @@
     pal_index++;
   }

-  for (uint8_t ss = 0; ss < NUM_STRIPS; ss++) {
+  for (int ss = 0; ss < NUM_STRIPS; ss++) {
     fill_palette(&(leds[ss*NUM_LED]), NUM_LED, pal_index, 6, gPalette, 60, LINEARBLEND);
   }