fix en codigo de arduino

fix en codigo de arduino

--- _arduino/ardu/ardu.ino
+++ _arduino/ardu/ardu.ino
@@ -1,9 +1,12 @@
 #include <math.h>
+// seting:START
 const int pinEstado = 13; // ledEstado
 const int pinX[] = {0,1,2,3}; // pin de motores
 const int pinY[] = {4,5,6,7}; // pin de motores
 const int pinZ[] = {8,9,10,11}; // pin de motores
-const int btnX=A5,btnY=A4,btnZ=A3;
+const int btnX=A5,btnY=A4,btnZ=A3;// finales de carrera
+float tiempo = 20; // tiempo entre pasos
+// seting:END

 bool bEstado = true,
 x=false,y=false,z=false; // usado para indicar estados
@@ -11,9 +14,7 @@
 int bx,by,bz,// variable para finales de carrera
 xyzp[] = {0,0,0}, // cantidad de pasos para cade eje
 xp=0,yp=0,zp=0,  // guardar ultimo paso usado
-ratardox=0,ratardoy=0,rx=0,ry=0,ratard2x=0,ratard2y=0,r2x=0,r2y=0;//guardar para desvio o angulos distintos a 45
-
-float tiempo = 20;
+retardox=0,retardoy=0,rx=0,ry=0,retardo2x=0,retardo2y=0,r2x=0,r2y=0;//guardar para desvio o angulos distintos a 45

 int i=0, inChar=0; String inString = "";
 bool comenzar = false;
@@ -62,27 +63,32 @@
     inString="";
   }
   if (inChar == '\n' || inChar == ';' ) {
+    // limpiar var de entrada
     i=0;
     inString = "";
+    //Analisis de pasos
     if(x==false||y==false||z==false){
       double auxX=0,auxY=0;
-      auxX = xyzp[0];
-      auxY = xyzp[1];
+      auxX = xyzp[0];// pasos de eje x
+      auxY = xyzp[1];// pasos de eje y
+      //si es negativo lo paso a positivo para la division
       if(auxX<0){auxX = auxX*-1;}
       if(auxY<0){auxY = auxY*-1;}
+      //descubir
       if(auxX<auxY){
-        ratardox = floor(auxY / auxX);
-        ratard2x = floor(auxY/auxY - auxX*floor(auxY / auxX));
-        ratardoy = 0;
+        retardox  = floor(auxY / auxX);
+        retardo2x = floor(auxY / auxY - auxX*floor(auxY / auxX));
+        retardoy  = 0;
       }else{
-        ratard2y = floor(auxX/auxX - auxY*floor(auxX / auxY));
-        ratardoy = floor(auxX / auxY);
-        ratardox = 0;
+        retardoy  = floor(auxX / auxY);
+        retardo2y = floor(auxX / auxY - auxY*floor(auxX / auxY));
+        retardox  = 0;
       }
-      rx=ratardox;
-      ry=ratardoy;
-      r2x=ratard2x;
-      r2y=ratard2y;
+
+      rx=retardox;
+      ry=retardoy;
+      r2x=retardo2x;
+      r2y=retardo2y;
       comenzar=true;
     }
   }
@@ -92,47 +98,47 @@

 if(comenzar){

-  if(ratardox==0){
-    if(ratard2x>0){ratard2x--;}
-    if(ratardoy>0){ratardoy--;}
-    ratardox=rx;
+  if(retardox==0){
+    if(retardo2x>0){retardo2x--;}
+    if(retardoy>0){retardoy--;}
+    retardox=rx;

     if(0<xyzp[0]){
       moverX(0);
-      if(ratard2x==0){
+      if(retardo2x==0){
         moverX(0);
-        ratard2x=r2x;
+        retardo2x=r2x;
       }
       estado();
     }
     if(0>xyzp[0]){
       moverX(1);
-      if(ratard2x==0){
+      if(retardo2x==0){
         moverX(1);
-        ratard2x=r2x;
+        retardo2x=r2x;
       }
       estado();
     }
   }

-  if(ratardoy==0){
-    if(ratard2y>0){ratard2y--;}
-    if(ratardox>0){ratardox--;}
-    ratardoy=ry;
+  if(retardoy==0){
+    if(retardo2y>0){retardo2y--;}
+    if(retardox>0){retardox--;}
+    retardoy=ry;

     if(0<xyzp[1]){
       moverY(0);
-      if(ratard2y==0){
+      if(retardo2y==0){
         moverY(0);
-        ratard2y=r2y;
+        retardo2y=r2y;
       }
       estado();
     }
     if(xyzp[1]<0){
       moverY(1);
-      if(ratard2y==0){
+      if(retardo2y==0){
         moverY(1);
-        ratard2y=r2y;
+        retardo2y=r2y;
       }
       estado();
     }


Faster reference clock rate (using pin 3), skip outer loop to slow PSK.

--- examples/PSK31-Transmit/PSK31-Transmit.ino
+++ examples/PSK31-Transmit/PSK31-Transmit.ino
@@ -5,10 +5,10 @@

 void setup() {
   Serial.begin(9600);
-  pinMode(11, OUTPUT);
+  pinMode(3, OUTPUT);
   pinMode(2, OUTPUT);
   // put your setup code here, to run once:
-  dds.setReferenceClock(8000);
+  dds.setReferenceClock(32000);
   dds.start();
   dds.setFrequency(1000);
   dds.on();
@@ -41,7 +41,7 @@
   //  return;
   for(i = 0; i < strlen(string); i++) {
     sendChar(string[i]);
-    Serial.println(string[i]);
+    //Serial.println(string[i]);
   }
 }

@@ -51,19 +51,25 @@

 // This will trigger at 8kHz
 ISR(ADC_vect) {
+  static uint8_t outer = 0;
   static uint8_t tcnt = 0;
   TIFR1 |= _BV(ICF1);
   // Wave shaping
-  PORTD |= _BV(2);
   // TODO: Improve how this would perform.
-  if(tcnt < 82)
-    dds.setAmplitude(amplitudeShape[(82-tcnt)/2]);
-  if(tcnt > (255-82))
-    dds.setAmplitude(amplitudeShape[(tcnt-173)/2]);
   //else if(tcnt > (255-64))
   //  dds.setAmplitude((255 - tcnt));
   //else dds.setAmplitude(255);
+  if(tcnt < 81)
+    dds.setAmplitude(amplitudeShape[(81-tcnt)/2]);
+  if(tcnt > (255-81))
+    dds.setAmplitude(amplitudeShape[(tcnt-174)/2]);
   dds.clockTick();
+  PORTD &= ~_BV(2);
+  if(outer++ == 3) {
+    outer = 0;
+  } else {
+    return;
+  }
   if(tcnt++ == 0) { // Next bit
     //PORTD ^= _BV(2); // Diagnostic pin (D2)
     if(!sent) {


Update HASwitchPlate.ino

Update HASwitchPlate.ino

--- Arduino_Sketch/HASwitchPlate/HASwitchPlate.ino
+++ Arduino_Sketch/HASwitchPlate/HASwitchPlate.ino
@@ -82,7 +82,13 @@
 const unsigned long telnetInputMax = 128;           // Size of user input buffer for user telnet session
 bool motionEnabled = false;                         // Motion sensor is enabled
 bool mdnsEnabled = true;                            // mDNS enabled
-bool beepEnabled = true;
+bool beepEnabled = true;                            // Keypress beep enabled
+unsigned long previousMillis = 0;                   // will store last time beep was updated
+long OnTime = 1000;                                 // milliseconds of on-time
+long OffTime = 1000;                                 // milliseconds of off-time
+boolean beepState;                                  // will store beepState true or false
+unsigned int beepCounter;                           // Count the number of beeps
+byte beepPin;                                       // define beep pin output
 uint8_t motionPin = 0;                              // GPIO input pin for motion sensor if connected and enabled
 bool motionActive = false;                          // Motion is being detected
 const unsigned long motionLatchTimeout = 30000;     // Latch time for motion sensor
@@ -108,7 +114,7 @@
 String mqttStatusTopic;                             // MQTT topic for publishing device connectivity state
 String mqttSensorTopic;                             // MQTT topic for publishing device information in JSON format
 String mqttLightCommandTopic;                       // MQTT topic for incoming panel backlight on/off commands
-String mqttBeepCommandTopic;                         // MQTT topic for error beep
+String mqttBeepCommandTopic;                        // MQTT topic for error beep
 String mqttLightStateTopic;                         // MQTT topic for outgoing panel backlight on/off state
 String mqttLightBrightCommandTopic;                 // MQTT topic for incoming panel backlight dimmer commands
 String mqttLightBrightStateTopic;                   // MQTT topic for outgoing panel backlight dimmer state
@@ -142,14 +148,9 @@

   if (beepEnabled)
   {
-    pinMode(4, OUTPUT);
-    beep(100);
-    beep(50);
-    beep(100);
-  }
-
-
-
+    beepPin = 4;
+    pinMode(beepPin, OUTPUT);
+  }
   pinMode(nextionResetPin, OUTPUT);
   digitalWrite(nextionResetPin, HIGH);
   Serial.begin(115200);  // Serial - LCD RX (after swap), debug TX
@@ -234,6 +235,22 @@
 void loop()
 { // Main execution loop

+ if (beepEnabled){                                        // Process Beeps
+    if((beepState == true) && (millis() - previousMillis >= OnTime) && ((beepCounter > 0)))
+    {
+      beepState = false;                                   // Turn it off
+      previousMillis = millis();                           // Remember the time
+      analogWrite(beepPin, 254);                           // start beep for OnTime
+      if(beepCounter > 0){beepCounter--;}                  // Update the beep counter.
+    }
+    else if ((beepState == false) && (millis() - previousMillis >= OffTime) && ((beepCounter >= 0)))
+    {
+      beepState = true;                                    // turn it on
+      previousMillis = millis();                           // Remember the time
+      analogWrite(beepPin, 0);                             // stop beep for OffTime
+    }
+  }
+
   if (nextionHandleInput())
   { // Process user input from HMI
     nextionProcessInput();
@@ -314,16 +331,21 @@

 ////////////////////////////////////////////////////////////////////////////////////////////////////

-void beep(unsigned char delayms){
-  analogWrite(4, 254);      // Almost any value can be used except 0 and 255
-                           // experiment to get the best tone
-  delay(delayms);          // wait for a delayms ms
-  analogWrite(4, 0);       // 0 turns it off
-  delay(delayms);          // wait for a delayms ms
-}
-
-
-
+String getValue(String data, char separator, int index)
+{
+    int found = 0;
+    int strIndex[] = { 0, -1 };
+    int maxIndex = data.length();
+
+    for (int i = 0; i <= maxIndex && found <= index; i++) {
+        if (data.charAt(i) == separator || i == maxIndex) {
+            found++;
+            strIndex[0] = strIndex[1] + 1;
+            strIndex[1] = (i == maxIndex) ? i+1 : i;
+        }
+    }
+    return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
+}

 void mqttConnect()
 { // MQTT connection and subscriptions
@@ -543,10 +565,15 @@
     configClearSaved();
   }
   else if (strTopic == (mqttCommandTopic + "/beep") || strTopic == (mqttGroupCommandTopic + "/beep"))
-  { // '[...]/device/command/factoryreset' == clear all saved settings)
-    beep(1000);
-    beep(100);
-    beep(100);
+  { // '[...]/device/command/beep')
+    String mqqtvar1 = getValue( strPayload, ',', 0);
+    String mqqtvar2 = getValue( strPayload, ',',1);
+    String mqqtvar3 = getValue( strPayload, ',',2);
+
+    OnTime = mqqtvar1.toInt();
+    OffTime = mqqtvar2.toInt();
+    beepCounter = mqqtvar3.toInt();
+
   }
   else if (strTopic.startsWith(mqttCommandTopic) && (strPayload == ""))
   { // '[...]/device/command/p[1].b[4].txt' -m '' == nextionGetAttr("p[1].b[4].txt")
@@ -707,8 +734,9 @@
       mqttClient.publish(mqttStateJSONTopic, mqttButtonJSONEvent);
       if (beepEnabled)
       {
-        pinMode(4, OUTPUT);
-        beep(100);
+      OnTime = 500;
+      OffTime = 100;
+      beepCounter = 1;
       }

     }


Cleaned up formatting of tabs vs spaces and general code style cleanup

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -2,9 +2,11 @@
 #include <SoftwareSerial.h>
 #include <Wire.h>

+// For the WDT sleep functionality.
 #include <avr/sleep.h>
 #include <avr/wdt.h>

+// Includes relevant to our project.
 #include "Sensors.h"
 #include "Heartbeat.h"
 #include "Network.h"
@@ -12,12 +14,11 @@
 #include "TimerOne.h"
 #include "SparkFunMPL3115A2.h"

-// global network object
+// Global because arduno says we need setup and loop functions.
 Network network;
-
-// global sensors object
 Sensors sensors;

+// Defines for our wifi credentials.
 #define SSID "OpenWrt"
 #define password "castle2004"

@@ -28,7 +29,7 @@
 	// Start up the serial communication.
 	// Find out why this cuts off the next serial print.
 	Serial.begin(115200);
-
+
 	for(int i = 0; i < 3; i++)
 		Serial.print(F("==============="));

@@ -37,41 +38,40 @@
 	for(int i = 0; i < 3; i++)
 		Serial.print(F("==============="));

-  // set pinmode for the CH_PD
-  pinMode(12, OUTPUT);
-  delay(3000);
-
-	 // Startup our network.
-  while (!network.init_wireless(SSID, password)){
-    Serial.println(F("Failed connecting to wireless network, retying in 3 seconds."));
-    Heartbeat::panic();
-    delay(3000);
-  }
-  delay(3000);
-
+	// set pinmode for the CH_PD
+	pinMode(12, OUTPUT);
+	delay(3000);
+
+	// Startup our network.
+	while (!network.init_wireless(SSID, password)){
+		Serial.println(F("Failed connecting to wireless network, retying in 3 seconds."));
+		Heartbeat::panic();
+		delay(3000);
+	}
+
 	// Startup a heartbeat LED.
 	Heartbeat::start();
+
+	// Extra delay for extra safety.
+	delay(3000);

 	// initiate DH11 sesnor at pin 2
 	sensors.init_DH11(2);

-  // Setup the pressure sensor.
-  sensors.init_MPL3115A2();
-
-
+	// Setup the pressure sensor.
+	sensors.init_MPL3115A2();
 }

 /**
  * @brief Main loop of our application to read sensors and send data to server.
  */
 void loop(){
-
-  // time stamp each iteration
-  Serial.print("************ Time now in millis: ");
-  Serial.print(millis());
-  Serial.println(" ************");
-
-        // Read our s.
+	// time stamp each iteration
+	Serial.print("************ Time now in millis: ");
+	Serial.print(millis());
+	Serial.println(" ************");
+
+	// Read our s.
 	Sensor_data sensor_data = sensors.read_sensors();

 	// Dump the info to our screen.
@@ -81,62 +81,69 @@
 	Serial.println(sensor_data.temperature_f);
 	Serial.print(F("Sensor light reading: "));
 	Serial.println(sensor_data.light);
-  Serial.print(F("Sensor pressure reading: "));
-  Serial.println(sensor_data.pressure);
+	Serial.print(F("Sensor pressure reading: "));
+	Serial.println(sensor_data.pressure);

-  // Make our heartbeat LED blink at a normal rate again if we were panicking earlier
-  // or it was shut off.
-  Heartbeat::start();
+	// Make our heartbeat LED blink at a normal rate again if we were panicking earlier
+	// or it was shut off.
+	Heartbeat::start();

-  // try to send 5 times, if 5 fail restart the module
-  for(int i = 0; i < 5; i++){
-    Serial.print("Trying to send data: ");
-    Serial.println(i);
-
-    if(!network.send_packet(sensor_data)){
-      if(i == 2){
-        // something went wrong with the connection - try to reconnect
-        // Startup our network.
-        while (!network.init_wireless(SSID, password)){
-          Serial.println(F("Failed connecting to wireless network, retying in 3 seconds."));
-          Heartbeat::panic();
-          delay(3000);
-        }
-        delay(3000);
-
-        // start panic mode
-        Heartbeat::panic();
-      }
-    }
-    else{
-      // Make our heartbeat LED blink at a normal rate again if we were panicking earlier.
-      Heartbeat::start();
-      break;
-    }
-  }
-
+	// try to send 5 times, if 5 fail restart the module
+	for(int i = 0; i < 5; i++){
+		Serial.print("Trying to send data: ");
+		Serial.println(i);
+
+		if(!network.send_packet(sensor_data)){
+			if(i == 2){
+				// something went wrong with the connection - try to reconnect
+				// Startup our network.
+				while (!network.init_wireless(SSID, password)){
+					Serial.println(F("Failed connecting to wireless network, retying in 3 seconds."));
+					Heartbeat::panic();
+					delay(3000);
+				}
+
+				delay(3000);
+
+				// start panic mode
+				Heartbeat::panic();
+			}
+		} else {
+			// Make our heartbeat LED blink at a normal rate again if we were panicking earlier.
+			Heartbeat::start();
+			break;
+		}
+	}
+
 	Serial.println(F("Waiting 1 min... - sleep time"));
-  delay(60000); // wait
+	delay(60000); // wait

-  // kill the led before taking measurements
-  Heartbeat::stop();
-
+	// kill the led before taking measurements
+	Heartbeat::stop();
 }

-// disable watchdog interrupt
+/**
+ * @brief Disable WDT.
+ */
 ISR(WDT_vect){
-  // disable the watchdog
-  wdt_disable();
+	// disable the watchdog
+	wdt_disable();
 }

+/**
+ * @brief Enables WDT to fire after a certain time.
+ *
+ * @param time_to_sleep How long till the WDT fires again.
+ */
 void EnableWatchDog(const byte time_to_sleep){
-  MCUSR = 0;
-  WDTCSR |= 0b00011000;
-  WDTCSR =  0b01000000 | time_to_sleep;
+	MCUSR = 0;
+	WDTCSR |= 0b00011000;
+	WDTCSR =  0b01000000 | time_to_sleep;

-  wdt_reset();
-  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
-  // sleep until we are interrupted
-  sleep_mode();
+	wdt_reset();
+
+	set_sleep_mode(SLEEP_MODE_PWR_DOWN);
+
+	// sleep until we are interrupted
+	sleep_mode();
 }
-


moved the object initializers to a global scope - its an embedded system, its ok :P

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -6,6 +6,12 @@
 #include "Network.h"
 #include "DHT.h"
 #include "TimerOne.h"
+
+// global network object
+Network network;
+
+// global sensors object
+Sensors sensors;

 void setup(){
 	// Start up the serial communication.
@@ -22,11 +28,11 @@
 	// Startup a heartbeat LED.
 	Heartbeat::start();

-	Sensors sensors;
+
 	sensors.init_DH11(2);

 	// Startup our network.
-	Network network;
+
 	while (!network.init_wireless("OpenWrt", "castle2004")){
 		Serial.println(F("Failed connecting to wireless network, retying in 3 seconds."));
 		Heartbeat::panic();


Add arduino stuff

Add arduino stuff

--- arduino/wifi_shield_test.ino
+++ arduino/wifi_shield_test.ino
@@ -1,118 +0,0 @@
-#include <Adafruit_CC3000.h>
-#include <Adafruit_CC3000_Server.h>
-#include <ccspi.h>
-
-/***************************************************
-  CC3000 Low Power Datalogging
-
-  Example 1: No Low Power Optimizations
-
-  Created by Tony DiCola (tony@tonydicola.com)
-
-  Designed specifically to work with the Adafruit WiFi products:
-  ----> https://www.adafruit.com/products/1469
-
-  Adafruit invests time and resources providing this open source code,
-  please support Adafruit and open-source hardware by purchasing
-  products from Adafruit!
-
-  Based on CC3000 examples written by Limor Fried & Kevin Townsend
-  for Adafruit Industries and released under a BSD license.
-  All text above must be included in any redistribution.
-
- ****************************************************/
-
-#include <Adafruit_CC3000.h>
-#include <SPI.h>
-
-// CC3000 configuration.
-#define ADAFRUIT_CC3000_IRQ    3
-#define ADAFRUIT_CC3000_VBAT   5
-#define ADAFRUIT_CC3000_CS     10
-
-// Wifi network configuration.
-#define WLAN_SSID              "FlatironSchool"
-#define WLAN_PASS              "33west26"
-#define WLAN_SECURITY          WLAN_SEC_WPA2
-
-// Data logging configuration.
-#define LOGGING_FREQ_SECONDS   30       // Seconds to wait before a new sensor reading is logged.
-
-#define SENSOR_PIN             0        // Analog pin to read sensor values from (for example
-                                        // from a photocell or other resistive sensor).
-
-#define SERVER_IP              192, 168, 3, 71    // Logging server IP address.  Note that this
-                                                   // should be separated with commas and NOT periods!
-
-#define SERVER_PORT            8000                // Logging server listening port.
-
-// Internal state used by the sketch.
-Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT);
-uint32_t ip;
-unsigned long lastSend = 0;
-
-// Take a sensor reading and send it to the server.
-void logSensorReading() {
-  // Take a sensor reading
-  int reading = analogRead(SENSOR_PIN);
-
-  // Connect to the server and send the reading.
-  Serial.print(F("Sending measurement: ")); Serial.println(reading, DEC);
-  Adafruit_CC3000_Client server = cc3000.connectTCP(ip, SERVER_PORT);
-  if (server.connected()) {
-    Serial.println("Connected!!");
-    server.println(reading);
-  }
-  else {
-    Serial.println(F("Error sending measurement!"));
-  }
-
-  // Wait a small period of time before closing the connection
-  // so the message is sent to the server.
-  delay(100);
-
-  // Close the connection to the server.
-  server.close();
-}
-
-void setup(void)
-{
-  Serial.begin(115200);
-
-  // Initialize the CC3000.
-  Serial.println(F("\nInitializing CC3000..."));
-  if (!cc3000.begin())
-  {
-    Serial.println(F("Couldn't begin()! Check your wiring?"));
-    while(1);
-  }
-  Serial.println(F("\nInitialized!"));
-  // Connect to AP.
-  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
-    Serial.println(F("Failed!"));
-    while(1);
-  }
-  Serial.println(F("Connected!"));
-
-  // Wait for DHCP to be complete.
-  Serial.println(F("Request DHCP"));
-  while (!cc3000.checkDHCP())
-  {
-    delay(100);
-  }
-
-  // Store the IP of the server.
-  ip = cc3000.IP2U32(SERVER_IP);
-
-  Serial.println(F("Setup complete."));
-}
-
-void loop(void)
-{
-  unsigned long time = millis();
-  if (time - lastSend >= (1000 * (unsigned long)LOGGING_FREQ_SECONDS)) {
-    logSensorReading();
-    lastSend = time;
-  }
-}
-


Strip trailing whitespace.

Strip trailing whitespace.

--- Arduino/coopController/coopController.ino
+++ Arduino/coopController/coopController.ino
@@ -464,7 +464,7 @@
 void handleSensorReadings() {
   // Temperature based reactions
   // ---------------------------
-
+
   // Ensure fan is on if temperature is at or above fan threshold.
   if (TempF >= fanThreshold) {
     if (!fanState) {
@@ -483,7 +483,7 @@
       toggleFan();
     }
   }
-
+
   // Ensure water heater is on if temperature is at or below heater threshold.
   if (TempF <= heaterThreshold) {
     if (!heaterState) {
@@ -502,7 +502,7 @@
       toggleHeater();
     }
   }
-
+
   // Light based reactions
   // ---------------------

@@ -569,7 +569,6 @@
     }
   }
 }
-

 /**
  * Door switch debouncer
@@ -615,7 +614,6 @@
   }
 }

-
 /**
  * Initialization on startup.
  */
@@ -712,7 +710,7 @@

   // Update door LEDs as needed
   doorLEDs();
-
+
   // Update the LCD display
   updateLCD();
 }


Delete pool_monitor.ino

Delete pool_monitor.ino

--- ESP8266-Pool_Monitor/pool_monitor.ino
+++ ESP8266-Pool_Monitor/pool_monitor.ino
@@ -1,413 +0,0 @@
-//Project: Monitor water level (HC-SR04P) of Balacing tank and the Temperature of Water (DS18b20) / Ambient (DHT22)
-//         Send alert via Blynk app if water level is too high, or water temperature is higher than 28 C
-
-/*
-//https://community.blynk.cc/t/water-tank-level-indicator-with-low-level-warning-notifications/26271
-
-//v1.0 - Wifi Manager + Blynk
-//v1.1 - added deep sleep function - https://community.blynk.cc/t/esp-deep-sleep/5622/13
-//v1.2 - added run time change of deep sleep interval via UI setup
-//v1.3 -
-
-//**** Blynk Virtual Pin Assignments****
-// V0 - Water temperature alert
-// V1 - Tank Height (cm)
-// V2 - Sensor distance from Tank (cm)
-// V3 - Temperature
-// V4 - Battery voltage
-// V6 - Numeric Widget - Sleep interval (mins)
-// V9 - Level V widget - Water Level %
-//V10 - Numeric Widget - Level exceed then will trigger Alert
-//V11 - Button Widget -  To enable / disable Alert
-//V12 - Distance - height from sensor to water level
-
-Hardware:
-1. Wemos D1 Pro
-2. DS18B20 Temperature Sensor
-3. Ultra Sonic Sensor
-4. 4.7k resistor - put between D4 and VCC
-
-
-Ultra sonic Sensor: Vcc - D7, Gnd - Gnd, Echo - D6, Trigger - D5
-DS18820 - Vcc - D8, Gnd - Gnd, Data - D4
-
-Todo
-----
-- if sonar sensor out of range --> don't save but Alert
-- water temperature alert
-
-*/
-
-#include <OneWire.h>
-#include <DallasTemperature.h>
-#include <ESP8266WiFi.h>
-#include <BlynkSimpleEsp8266.h>
-
-char auth[] = "X2Z4r2nC8AxFGrZQqMhbhBbCgVCtOnhl";
-
-char ssid[] = "dongdaemum";
-char pass[] = "1111111111";
-
-BlynkTimer timer;
-
-//HC-SR04 ultra sonic sensor
-#define trigPin D5  // Trigger Pin
-#define echoPin D6  // Echo Pin
-#define RadarPowerPin D7 //GPIO12 = D6, GPIO14 = D5, GPIO15 = D8
-
-//DS18820 temperature sensor
-#define sensorPin D4
-#define TempPowerPin D8
-
-#define filterSamples   15              // filterSamples should  be an odd number, no smaller than 3
-
-int alertLevelCounter = 0; //Counter starts at zero
-//int volume1; // for smoothing algorithum
-double wLevel; // for smoothing algorithum
-int levelAlert;
-int wateralert = 0;
-//int sensSmoothArray1 [filterSamples];   // array for holding raw sensor values for sensor1
-int smoothDistance;                     // variables for sensor1 data
-
-//double alertInMin = 0.5;                //Alert time following alert water level being reached (0.5 = 30secs)
-//const int alertDuration = 2;            //Alert sent every 2 minutes
-
-int checkFreq = 2;                //how often run the check / sleep for how long before wake up, in mins
-int tankHeight = 100;             //tank's height
-int heightFrTank = 20;            //sensor distance from tank
-long duration, distance;          // Duration used to calculate distance
-
-//init DS11820
-OneWire oneWire(sensorPin);
-DallasTemperature DS18B20(&oneWire);
-float temp;
-float volt;
-
-BLYNK_CONNECTED() { // runs once at device startup, once connected to server.
-  Blynk.syncVirtual(V1);
-  Blynk.syncVirtual(V2);
-  Blynk.syncVirtual(V6);
-  Blynk.syncVirtual(V10);
-  Blynk.syncVirtual(V11);
-}
-
-BLYNK_WRITE(V1) {
-  tankHeight = param.asInt();
-  Serial.print("\nTank's Height: ");
-  Serial.println(tankHeight);
-  Serial.println();
-}
-
-BLYNK_WRITE(V2) {
-  heightFrTank = param.asInt();
-  Serial.print("Height from Tank: ");
-  Serial.println(heightFrTank);
-  Serial.println();
-}
-
-BLYNK_WRITE(V6) {
-  checkFreq = param.asInt();
-  Serial.print("Sleep Interval: ");
-  Serial.println(checkFreq);
-  Serial.println();
-}
-
-BLYNK_WRITE(V10) {
-  levelAlert = param.asInt();
-  Serial.print("Water Level Alert: ");
-  Serial.println(levelAlert);
-  Serial.println();
-}
-
-BLYNK_WRITE(V11) {
-
-  int alertOff = param.asInt();
-
-  if(alertOff == 0) {
-    resetWaterLevelAlert();
-    wateralert = 1;
-    Serial.print("Level Alert is OFF.");
-    Serial.println();
-  }
-  else {
-    resetWaterLevelAlert();
-    wateralert = 0;
-    Serial.print("Level Alert is ON.");
-    Serial.println();
-  }
-
-}
-
-void resetWaterLevelAlert() {
-  alertLevelCounter = 0;
-  wateralert = 0;
-}
-
-void checkWaterLevel() {
-  Serial.print("Water Level (%) = ");
-  Serial.println(wLevel);
-  Serial.print("Level Alert (%) = ");
-  Serial.println(levelAlert);
-  Serial.print("Alert (1 = off, 0 = on) = ");
-  Serial.println(wateralert);
-
-  if(wLevel > levelAlert && wateralert == 0){
-//    alertLevelCounter += 1;
-    Blynk.notify("Water Tank Level Alert"); // send push notification to blynk app
-
-  }
-
-//  if(alertLevelCounter > alertInMin * 60 && wateralert == 0){
-//    Blynk.notify("Water Tank Level Alert"); // send push notification to blynk app
-//    wateralert = 1;
-//    resetWaterLevelAlert();
-//  }
-}
-
-void MeasureCmForSmoothing() {
-
-  //take multiple reading
-
-  digitalWrite(RadarPowerPin, HIGH);  //provide power
-  delay(1000);
-
-    smoothDistance = mesureDistance();
-
-  digitalWrite(RadarPowerPin, LOW);  //turn off power
-  delay(100);
-
-  Serial.print("Smoothed Distance: ");
-  Serial.println(smoothDistance);
-
-  //tank height 100 cm, sensor is 20 cm above the tank
-  wLevel = (tankHeight + heightFrTank - smoothDistance);
-
-  Serial.print("Water Level (cm): ");
-  Serial.println(wLevel);
-
-  //convert to %
-  wLevel = wLevel / tankHeight * 100;
-
-  Serial.print("Water Level (%): ");
-  Serial.println(wLevel);
-
-  Blynk.virtualWrite(V12, smoothDistance); // virtual pin
-  Blynk.virtualWrite(V9, wLevel); // virtual pin
-  delay(1000);
-}
-
-void UploadMeasureCmForSmoothing() {
-
-  Blynk.virtualWrite(V3, temp); // Water level %
-  Blynk.virtualWrite(V4, volt); // battery
-  Blynk.virtualWrite(V9, wLevel); // Water level %
-  Blynk.virtualWrite(V12, smoothDistance); // virtual pin
-
-}
-
-
-void setup() {
-  Serial.begin(115200);
-  Blynk.begin(auth, ssid, pass);
-
-  pinMode(trigPin, OUTPUT);
-  pinMode(echoPin, INPUT);
-  //pin to provide power to ultra sonic sensor
-  pinMode(RadarPowerPin, OUTPUT);
-
-  //pin to provide power to temperature sensor
-  pinMode(TempPowerPin, OUTPUT);
-
-  Serial.println("Measure Water Temperature");
-  measurementEvent();
-
-  Serial.println("\nMeasure Water Level");
-  MeasureCmForSmoothing();
-
-  Serial.println("Upload Data");
-  UploadMeasureCmForSmoothing();
-
-  Serial.println("check WaterLevel Alert");
-  checkWaterLevel();
-
-  goToSleep();
-
-}
-
-void loop() {
-
-}
-
-int digitalSmooth(int rawIn, int *sensSmoothArray){     // "int *sensSmoothArray" passes an array to the function - the asterisk indicates the array name is a pointer
-int j, k, temp, top, bottom;
-long total;
-static int i;
-// static int raw[filterSamples];
-static int sorted[filterSamples];
-boolean done;
-
-i = (i + 1) % filterSamples;    // increment counter and roll over if necc. -  % (modulo operator) rolls over variable
-sensSmoothArray[i] = rawIn;                 // input new data into the oldest slot
-
-// Serial.print("raw = ");
-
- for (j=0; j<filterSamples; j++){     // transfer data array into anther array for sorting and averaging
-     sorted[j] = sensSmoothArray[j];
- }
-
-   done = 0;                // flag to know when we're done sorting
- while(done != 1){        // simple swap sort, sorts numbers from lowest to highest
-      done = 1;
-        for(j = 0; j < (filterSamples - 1); j++){
-           if(sorted[j] > sorted[j + 1]){     // numbers are out of order - swap
-             temp = sorted[j + 1];
-             sorted [j+1] =  sorted[j] ;
-             sorted [j] = temp;
-             done = 0;
-           }
-        }
-  }
-
-   // throw out top and bottom 15% of samples - limit to throw out at least one from top and bottom
-   //  bottom = max(((filterSamples * 15)  / 100), 1);
-   //  top = min((((filterSamples * 85) / 100) + 1  ), (filterSamples - 1));   // the + 1 is to make up for asymmetry caused by integer rounding
-   bottom = max(((filterSamples * 20)  / 100), 1);
-   top = min((((filterSamples * 80) / 100) + 1  ), (filterSamples - 1));   // the + 1 is to make up for asymmetry caused by integer rounding
-   k = 0;
-   total = 0;
-  for( j = bottom; j< top; j++){
- total += sorted[j];  // total remaining indices
- k++;
- //Serial.print(sorted[j]);
- //Serial.print("   ");
- //terminal.print(sorted[j]);
- //terminal.println("   ");
-
-  }
-   //terminal.print("average: ");
-   //terminal.println(total/k);
-   //terminal.flush();
-   //Serial.println();
-   //Serial.print("average = ");
-   //Serial.println(total/k);
-  return total / k;    // divide by number of samples
-}
-
-int mesureSingleDistance() {
-      long duration, distance;
-
-      digitalWrite(trigPin, LOW);
-      delayMicroseconds(2);
-      digitalWrite(trigPin, HIGH);
-      delayMicroseconds(10);
-      digitalWrite(trigPin, LOW);
-      duration = pulseIn(echoPin, HIGH);
-      distance = (duration/2) / 29.1;
-
-      Serial.print("Distance: ");
-      Serial.println(distance);
-
-      return distance;
-  }
-
-/**
- * mresure distnce average delay 10ms
- */
-int mesureDistance() {
-    const int ULTRASONIC_MIN_DISTANCE = heightFrTank;  //20
-    const int ULTRASONIC_MAX_DISTANCE = tankHeight + heightFrTank;  //120
-
-      int i, total_count = 0, total_distance = 0, distance, values[10], average, temp, new_count = 0;
-
-      for(i=0; i<5; i++){
-          distance = mesureSingleDistance();
-          //check if out of range
-          if(distance > ULTRASONIC_MIN_DISTANCE && distance < ULTRASONIC_MAX_DISTANCE) {
-              total_distance += distance;
-              values[total_count++]=distance;
-              Serial.printf("Value %d...\n", distance);
-          }
-      }
-
-      Serial.print("total_count = ");
-      Serial.println(total_count);
-      if(total_count > 0) {
-
-          average = total_distance / total_count;
-          total_distance = 0;
-          Serial.printf("Average %d...\n", average);
-
-          for(i=0; i<total_count; i++){
-              temp = (average - values[i])*100/average;
-              Serial.printf("Analyze %d....%d...\n", values[i],temp);
-              if(temp < 10 && temp > -10){
-                  total_distance += values[i];
-                  new_count++;
-              }
-          }
-
-          if(new_count > 0) {
-//              Serial.print("total_distance = ");
-//              Serial.println(total_distance);
-//              Serial.print("new_count = ");
-//              Serial.println(new_count);
-              return total_distance / new_count;
-          }
-      }
-      Serial.println("Sonar sensor out of range");
-      return 0;  //return 0 meaning the sensor out of range
-  }
-
-void goToSleep() {
-  // calculate required sleep time and go to sleep
-
-  Serial.print(" Going to sleep now for ");
-  Serial.print(checkFreq);
-  Serial.println(" mins");
-
-  ESP.deepSleep(checkFreq * 60 * 1000000); //deepSleep is microseconds 1 sec = 1000000
-  delay(100);
-
-} // end of void goToSleep()
-
-void measurementEvent() {
-
-
-  //******Measure Water Temperature*********************************************
-  digitalWrite(TempPowerPin, HIGH);  //provide power
-  delay(2000);
-
-  DS18B20.begin();
-  DS18B20.requestTemperatures();
-  temp = DS18B20.getTempCByIndex(0); // Celcius
-  Serial.print("Temperature (C) = ");
-  Serial.println(temp);
-
-  digitalWrite(TempPowerPin, LOW);  //turn off power
-  delay(100);
-
-  //******Battery Voltage Monitoring*********************************************
-  //depend on 220k or 100k resistor used, toggle between this 2 calculation
-
-  // using 220k
-  // Voltage divider R1=100k, R2 = (220k + 100k) + 220k = 540k
-  // Calculation to get the factor: 4.2v * 100/540 = 0.7777, 0.7777 * y = 4.2, y = 5.4
-//  float calib_factor = 5.28; // change this value to calibrate the battery voltage, 5.28 is so call calibrated
-//  float calib_factor = 5.4;
-
-  // using 100k
-  // Voltage divider R1 = 100k, R2 = (220k + 100k) + 100k = 420k;
-  // Calculation to get the factor: 4.2v * 100/420 = 1, 1 * y = 4.2, y = 4.2
-  float calib_factor = 4.2;
-
-  unsigned long raw = analogRead(A0);
-//  Serial.print("raw analog = ");
-//  Serial.println(raw);
-  float volt = raw * calib_factor/1024;
-
-  Serial.print( "\nVoltage = ");
-  Serial.print(volt, 2); // print with 2 decimal places
-  Serial.println (" V");
-
- //*******************************************************************************
-}


Minor Changes

Minor Changes

Added some pin checking, changed the motorLevel array slightly.

--- embedded/SerialCommander/SerialCommander.ino
+++ embedded/SerialCommander/SerialCommander.ino
@@ -54,6 +54,10 @@
 #define angleLowest 30 //The minimum allowable angle
 #define angleHighest 150 //The maximum allowable angle

+#define motorLevel1 255 //PWM levls for the motors
+#define motorLevel2 255
+#define motorLevel3 255
+
 // Libraries & Objects
 /*******************************************************************************************/
 #include <Servo.h>
@@ -72,7 +76,7 @@
 const byte motorPins[] = {
   0,pinMotor1,pinMotor2,pinMotor3}; //A map for the solenoid pins
 const byte motorLevel[] = {
-  0,255,255,255}; //Individual PWM signal levels for each motor
+  0,motorLevel1,motorLevel2,motorLevel3}; //Individual PWM signal levels for each motor

 // Global Variables
@@ -117,8 +121,6 @@
   Serial.println(F("To start the motor on shooter 2, type: '2 m'\n"));

-
-
   //Attach the servo objects
   servo1.attach(pinServo1,900,2100); //Include the maximum and minimum pulse widths.
   servo2.attach(pinServo2,900,2100);
@@ -126,11 +128,6 @@

   //Wait until 'Game Start' button is pressed
-
-  //Set up the PWM DC motor control signals
-  analogWrite(pinMotor1,motorLevel1);
-  analogWrite(pinMotor2,motorLevel2);
-  analogWrite(pinMotor3,motorLevel3);

 }
@@ -179,19 +176,19 @@
     case '1':
       executeCommand(1,StringIn);
       break;
-
+
     case 'B':
     case 'b':
     case '2':
       executeCommand(2,StringIn);
       break;
-
+
     case 'C':
     case 'c':
     case '3':
       executeCommand(3,StringIn);
       break;
-
+
     default:
       Serial.println("First character not recognized");
     }
@@ -277,16 +274,23 @@
 //This function releases one BB (hopefully) from shooter <shooterNum>
 void releaseBall(byte shooterNum) {

-
   Serial.print("Releasing ball from shooter: ");
   Serial.println(shooterNum);

-
-  digitalWrite(solenoidPins[shooterNum],HIGH); //Activate the solenoid: open the passage
-
-  ballReleaseTimer[shooterNum]=millis()+ballReleaseTime; //Set the timer for deactivating the solenoid
-  ballReleasing[shooterNum]=1; //Indicate that we are releasing a ball
-}
+  if (shooterNum<1 || shooterNum>3) { //Check that the shooter number is valid
+    Serial.print("Unrecognized shooter Num: ");
+    Serial.println(shooterNum);
+    //Send unrecognized shooter num feedback to laptop
+    sendMessage(0xE1,shooterNum);
+  }
+  else{
+    digitalWrite(solenoidPins[shooterNum],HIGH); //Activate the solenoid: open the passage
+
+    ballReleaseTimer[shooterNum]=millis()+ballReleaseTime; //Set the timer for deactivating the solenoid
+    ballReleasing[shooterNum]=1; //Indicate that we are releasing a ball
+  }
+}
+

 /*▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
 /*checkSolenoids
@@ -311,4 +315,5 @@

+


Removed Firmata code in loop()

Removed Firmata code in loop()

--- examples/StandardFirmata/StandardFirmata.ino
+++ examples/StandardFirmata/StandardFirmata.ino
@@ -608,62 +608,60 @@

 void systemResetCallback()
 {
-  // initialize a defalt state
-  // TODO: option to load config from EEPROM instead of default
-  if (isI2CEnabled) {
-  	disableI2CPins();
-  }
-  for (byte i=0; i < TOTAL_PORTS; i++) {
-    reportPINs[i] = false;      // by default, reporting off
-    portConfigInputs[i] = 0;	// until activated
-    previousPINs[i] = 0;
-  }
-  // pins with analog capability default to analog input
-  // otherwise, pins default to digital output
-  for (byte i=0; i < TOTAL_PINS; i++) {
-    if (IS_PIN_ANALOG(i)) {
-      // turns off pullup, configures everything
-      setPinModeCallback(i, ANALOG);
-    } else {
-      // sets the output to 0, configures portConfigInputs
-      setPinModeCallback(i, OUTPUT);
-    }
-  }
-  // by default, do not report any analog inputs
-  analogInputsToReport = 0;
-
-  /* send digital inputs to set the initial state on the host computer,
-   * since once in the loop(), this firmware will only send on change */
-  /*
-  TODO: this can never execute, since no pins default to digital input
-        but it will be needed when/if we support EEPROM stored config
-  for (byte i=0; i < TOTAL_PORTS; i++) {
-    outputPort(i, readPort(i, portConfigInputs[i]), true);
-  }
-  */
+  /* ToDo: Implement this but the nRF8001 uses many of these pins! */
+
+//  // initialize a defalt state
+//  // TODO: option to load config from EEPROM instead of default
+//  if (isI2CEnabled) {
+//  	disableI2CPins();
+//  }
+//  for (byte i=0; i < TOTAL_PORTS; i++) {
+//    reportPINs[i] = false;      // by default, reporting off
+//    portConfigInputs[i] = 0;	// until activated
+//    previousPINs[i] = 0;
+//  }
+//  // pins with analog capability default to analog input
+//  // otherwise, pins default to digital output
+//  for (byte i=0; i < TOTAL_PINS; i++) {
+//    if (IS_PIN_ANALOG(i)) {
+//      // turns off pullup, configures everything
+//      setPinModeCallback(i, ANALOG);
+//    } else {
+//      // sets the output to 0, configures portConfigInputs
+//      setPinModeCallback(i, OUTPUT);
+//    }
+//  }
+//  // by default, do not report any analog inputs
+//  analogInputsToReport = 0;
+//
+//  /* send digital inputs to set the initial state on the host computer,
+//   * since once in the loop(), this firmware will only send on change */
+//  /*
+//  TODO: this can never execute, since no pins default to digital input
+//        but it will be needed when/if we support EEPROM stored config
+//  for (byte i=0; i < TOTAL_PORTS; i++) {
+//    outputPort(i, readPort(i, portConfigInputs[i]), true);
+//  }
+//  */
 }

 void setup()
 {
+  Firmata.setFirmwareVersion(FIRMATA_MAJOR_VERSION, FIRMATA_MINOR_VERSION);
+
+  Firmata.attach(ANALOG_MESSAGE,  analogWriteCallback);
+  Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback);
+  Firmata.attach(REPORT_ANALOG,   reportAnalogCallback);
+  Firmata.attach(REPORT_DIGITAL,  reportDigitalCallback);
+  Firmata.attach(SET_PIN_MODE,    setPinModeCallback);
+  Firmata.attach(START_SYSEX,     sysexCallback);
+  Firmata.attach(SYSTEM_RESET,    systemResetCallback);
+
   Serial.begin(115200);
   Serial.println(F("Arduino setup"));
-  uart.begin();
-
-//  Firmata.setFirmwareVersion(FIRMATA_MAJOR_VERSION, FIRMATA_MINOR_VERSION);
-//
-//  Firmata.attach(ANALOG_MESSAGE, analogWriteCallback);
-//  Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback);
-//  Firmata.attach(REPORT_ANALOG, reportAnalogCallback);
-//  Firmata.attach(REPORT_DIGITAL, reportDigitalCallback);
-//  Firmata.attach(SET_PIN_MODE, setPinModeCallback);
-//  Firmata.attach(START_SYSEX, sysexCallback);
-//  Firmata.attach(SYSTEM_RESET, systemResetCallback);
-//
-//  Serial.begin(115200);
-//  Serial.println(F("Arduino setup"));
-//
-//  Firmata.begin(uart);
-//  systemResetCallback();  // reset to default config
+
+  Firmata.begin(uart);
+  systemResetCallback();  // reset to default config
 }

 /*==============================================================================
@@ -671,16 +669,17 @@
  *============================================================================*/
 void loop()
 {
+  // Handle any buffered ACI events from BLE
+  // ---------------------------------------
   uart.pollACI();
-
+
+//  // Process Firmata Messages, etc.
+//  // ------------------------------
 //  byte pin, analogPin;
 //
 //  /* DIGITALREAD - as fast as possible, check for changes and output them to the
 //   * FTDI buffer using Serial.print()  */
-//  checkDigitalInputs();
-//
-//  /* Handle any buffered ACI events from BLE */
-//  uart.pollACI();
+//  checkDigitalInputs();
 //
 //  /* SERIALREAD - processing incoming messagse as soon as possible, while still
 //   * checking digital inputs.  */


Midwest 2016

Midwest 2016

Clarified units, cleaned variable layout on the way there.  Minor
tweaks.  Significant change is addition of a hard-coded alliance color
gradient in setup(), because we couldn't establish RoboRIO-Arduino
serial connection and didn't have time to spend troubleshooting lights.

--- csarc/csarc.ino
+++ csarc/csarc.ino
@@ -1,31 +1,36 @@
 /* csarc allows you to do do a couple things with newline-terminated commands:
  *
- *  set a constant color value: "V#FFFFFF"
- *  make gradient pulses between two colors: "G#000000:#FFFFFF:pulseTime"
- *    \--loop between two colors: "L#000000:#FFFFFF:pulseTime"
- *    \--smooth loop between two colors: "S#000000:#FFFFFF:pulseTime
- *  start flashing between two colors:     "F#000000:#FFFFFF:pulseTime"
- *  lock for a period of time: "DIS:waitTime"
+ *  set a constant color value: ------------- "V#FFFFFF"
+ *  make gradient pulses between two colors:- "G#000000:#FFFFFF:pulseTime"
+ *    \--loop gradient between two colors: -- "L#000000:#FFFFFF:pulseTime"
+ *    \--smooth loop between two colors: ---- "S#000000:#FFFFFF:pulseTime
+ *  start flashing two colors --------------- "F#000000:#FFFFFF:pulseTime"
  *
- *  Change SINGLE_LED and the color pins to match your hardware.
+ *  To use, toggle GROVE_DRIVER or set the color pins to match your hardware.
  *  You can toggle a handy debug mode with "d".
  */
-// TO DO: implement start/stop flashing //done
-// TO DO: implement smooth gradients // done
-// TO DO: implement verbosity levels
+// TO DO: cut off timeout gradient when activity resumes
+//        implement verbosity levels
+//        evaluate memory gain from using #define for some constants

 #include <stdarg.h>

+// JUMPER SETUP FOR COMP
+
+
+
 // -------------  LED SETUP -------------
-#include <RGBdriver.h>
-const int CLK = 2; //definitions for
-const int DIO = 3; //Grove driver
+const boolean GROVE_DRIVER = false; // Grove LED driver or DFRobot shield?
+
+#include <RGBdriver.h> // Grove driver
+const int CLK = 2;
+const int DIO = 3;
 RGBdriver Driver(CLK,DIO);
-const boolean SINGLE_LED = true; // Grove LED driver or DFRobot shield?
-const int R_PIN = 10; // pins for
-const int G_PIN = 11; // directly driven
-const int B_PIN =  9; // setup
-int GND = 7; // ( <-for wiring convenience)
+
+const int R_PIN = 10; // pins for directly
+const int G_PIN = 11; // driven setup or
+const int B_PIN =  9; // DFRobot shield
+const int EXTRA_GND = 7; // <- for wiring convenience

 // --------- CONSTANTS + CONFIG ---------
 const int   OFF[] = {0,   0,   0 };
@@ -34,45 +39,51 @@
 const int  BLUE[] = {0,   0,   255};
 const int WHITE[] = {255, 255, 255};
 const int BAUDRATE = 19200;
-const int SERIAL_BUFFER_LENGTH = 128;
-const int SERIAL_CYCLE_LENGTH = 70;
-const int TIMEOUT = 600;  //timeout in seconds before beginning default pattern
-const float numdivs = 60.0; //change this to adjust gradient smoothness
+const int SERIAL_BUFFER_LENGTH = 32;  //leaves 15 characters for pulseTime
+const int SERIAL_CYCLE_LENGTH_MS = 70;
+const int TIMEOUT_S = 600;  //seconds of no activity before beginning default pattern
+const boolean TIMEOUT_ENABLED = false; // timeout is buggy
+const float numdivs = 60.0; //tune this to adjust gradient smoothness

 // ---------- GLOBAL VARIABLES ----------
 boolean debugMode = false;
 char inputBuffer[SERIAL_BUFFER_LENGTH];
-float gradPerc, gradPercPerTick, gradDelayPerTick;
-int gradcol1[3], gradcol2[3];
-boolean gradientLoop = false, recentActivity = false;
-boolean gradientMode = true; // true = back-and-forth, false = skipping
-
-int flashcol1[3], flashcol2[3];
-boolean flashLoop = true, flashFirstColor = false;
-int flashTime;
+boolean recentActivity = false;

 int red,green,blue;
 int* rgb[4] = {&red, &green, &blue, 0};

+int gradcol1[3], gradcol2[3];
+float gradPerc, gradPercPerTick, gradDelayPerTick_ms;
+boolean gradientLoop = false, gradientReversingMode = true;
+
+int flashcol1[3], flashcol2[3];
+int flashTimePerColor_ms;
+boolean flashLoop = true, flashingFirstColor = false;
+
 // -------------- THREADS ---------------
 #include <TimedAction.h>
-TimedAction   serialThread = TimedAction(2*SERIAL_CYCLE_LENGTH, SERIAL_CYCLE_LENGTH, &processSerialIn);
+TimedAction   serialThread = TimedAction(0, SERIAL_CYCLE_LENGTH_MS, &processSerialIn);
 TimedAction gradientThread = TimedAction(0,  &gradientStep); // initially disabled in setup()
-TimedAction  timeoutThread = TimedAction(TIMEOUT*1000, TIMEOUT*1000,  &timeoutAction);
-TimedAction    flashThread = TimedAction(0, flashTime, &flash); // initially disabled in setup()
+TimedAction    flashThread = TimedAction(0, flashTimePerColor_ms, &flash); // initially disabled in setup()
+TimedAction  timeoutThread = TimedAction(TIMEOUT_S * 1000, TIMEOUT_S * 1000,  &timeoutAction);

 void setup() {
-  if (SINGLE_LED) {
+  if (!GROVE_DRIVER) {
     pinMode(R_PIN,OUTPUT);
     pinMode(G_PIN,OUTPUT);
     pinMode(B_PIN,OUTPUT);
-    pinMode(GND,OUTPUT);
+    pinMode(EXTRA_GND,OUTPUT);
   }
   gradientThread.disable();
   flashThread.disable();
-  Serial.setTimeout(SERIAL_CYCLE_LENGTH/7); //should be substantially less than serialThread's execution window
+  if (!TIMEOUT_ENABLED) { timeoutThread.disable(); }
+  Serial.setTimeout(SERIAL_CYCLE_LENGTH_MS/7); //should be substantially less than serialThread's execution window
   Serial.begin(BAUDRATE);
-  quickCycle(25); // power-up notification
+  quickCycle(150); // power-up notification
+  gradientPulseSetup(BLUE,OFF,2);
+  gradientLoop = true;
+  gradientReversingMode = true;
 }

 void loop() {
@@ -84,7 +95,7 @@

 void processSerialIn() {
   Serial.readBytesUntil('\n',inputBuffer,SERIAL_BUFFER_LENGTH);
-  if (inputBuffer!="") {
+  if (inputBuffer[0]!=0) {
     recentActivity = true;
 //    if (debugMode) { Serial.print("|");
 //                     for (int x=0; x<10; x++) { Serial.print(inputBuffer[x]); }
@@ -93,7 +104,8 @@
     switch (inputBuffer[0]) {
       case 'd': { toggleDebug(); break; }
       case 'V': { processColor(); break; } // set value specified in V#FFFFFF input
-      case 'L' : { gradientLoop = true; processGradient(); break;}
+      case 'S' : { gradientLoop = true; gradientReversingMode = true;  processGradient(); break;}
+      case 'L' : { gradientLoop = true; gradientReversingMode = false;  processGradient(); break;}
       case 'G' : { gradientLoop = false; processGradient(); break;}
       case 'F' : { processFlash(); break; }
     }
@@ -190,7 +202,7 @@

     decodeHex(hex1,col1p);
     decodeHex(hex2,col2p);
-    float timeVal = atol(timev); //use strtol or sscanf instead
+    float timeVal = atof(timev); //use strtol or sscanf instead
     gradientPulseSetup(col1,col2,timeVal);

     if (debugMode) {
@@ -222,19 +234,21 @@
     int *col2p[4] = {&col2[0],&col2[1],&col2[2],0};
     decodeHex(hex1,col1p);
     decodeHex(hex2,col2p);
-    float timeVal = atol(timev); //use strtol or sscanf instead
+    float timeVal = atof(timev); //use strtol or sscanf instead
     flashSetup(col1,col2,timeVal);
   }
 }

 void flashSetup (const int col1[3],const int col2[3], float timev) {
-  flashTime = (float) timev*1000;
+  if (redundantFlashCommand(col1,col2, timev*1000)) { return;}
+  gradientThread.disable();
+  flashTimePerColor_ms = (float) timev*1000;
   for (int x=0; x<3; x++) {
     flashcol1[x]=col1[x];
     flashcol2[x]=col2[x];
   }

-  flashThread.setInterval(flashTime);
+  flashThread.setInterval(flashTimePerColor_ms);
   flashThread.reset();
   flashThread.enable();
   if (debugMode) {
@@ -244,27 +258,28 @@
 }

 void flash() {
-  if (debugMode) { Serial.print("Flash:");}
-  outputColor( flashFirstColor ? flashcol1 : flashcol2 );
-  flashFirstColor = !flashFirstColor;
-  if (debugMode) { Serial.print(red); Serial.print(green); Serial.println(blue); }
+//  if(debugMode) { Serial.print("Flash: ");}
+  outputColor( flashingFirstColor ? flashcol1 : flashcol2 );
+  flashingFirstColor = !flashingFirstColor;
+  // refactor to be able to use printColors()
+//  if (debugMode) {Serial.println(millis());}
 }

 void timeoutAction() {
   if (debugMode) { Serial.println("Processing timeout."); }
   if (!recentActivity) {
-    Serial.print("No recent activity for "); Serial.print(TIMEOUT); Serial.println(" seconds.");
+    Serial.print("No recent activity for "); Serial.print(TIMEOUT_S); Serial.println(" seconds.");
     // maybe timeout and timeout behavior should be configurable over serial.
     // low priority, bc this will mostly be running before serial comms have
     // been established.
-    gradientPulseSetup(OFF, WHITE, 2);
-    gradientLoop = true;
+    gradientLoop = false;
+    gradientPulseSetup(OFF, WHITE, TIMEOUT_S);
   }
 }

-void gradientPulseSetup (const int col1[3],const int col2[3], float timev) { // timev is now in seconds
+void gradientPulseSetup (const int col1[3],const int col2[3], float timev) {
   flashThread.disable();
-  gradDelayPerTick = (float) timev*1000/numdivs;
+  gradDelayPerTick_ms = (float) timev*1000/numdivs;
   gradPercPerTick = (float) 1/numdivs;
   gradPerc = 0;
   if (debugMode) {
@@ -283,8 +298,8 @@
     Serial.println(timev);
     Serial.print("numdivs = ");
     Serial.println(numdivs);
-    Serial.print("gradDelayPerTick = ");
-    Serial.println(gradDelayPerTick);
+    Serial.print("gradDelayPerTick_ms = ");
+    Serial.println(gradDelayPerTick_ms);
     Serial.print("gradPercPerTick = ");
     Serial.println(gradPercPerTick);
     Serial.println();
@@ -295,7 +310,7 @@
     gradcol2[x]=col2[x];
   }

-  gradientThread.setInterval(gradDelayPerTick);
+  gradientThread.setInterval(gradDelayPerTick_ms);
   gradientThread.reset();
   gradientThread.enable();
   if (debugMode) {
@@ -317,7 +332,7 @@
   else {
     if (gradientLoop) {
       gradPerc = 0;
-      if (gradientMode) {
+      if (gradientReversingMode) {
         int temp[3]; //swap 1 and 2
         arrayCopy(temp,gradcol1,3);
         arrayCopy(gradcol1,gradcol2,3);
@@ -369,7 +384,7 @@

 void outputColor( int r, int g, int b) {

-  if (!SINGLE_LED) {
+  if (GROVE_DRIVER) {
     Driver.begin();
     Driver.SetColor(r, g, b);
     Driver.end();
@@ -431,7 +446,7 @@
   *ptr = 0;
 }

-void quickCycle(int baseTime) {
+void rgbFlash(int baseTime) {
   setValue(255,0,0);
   delay(baseTime);
   setValue(0,255,0);
@@ -443,6 +458,16 @@
   setValue(0,0,0);
 }

+void quickCycle(int totalTime_ms) {
+/*  |-----------1/2 R/G/B/W pulse-----------|-----1/4 pulse-----|--1/8 pulse--|-1/8 grad->off-| */
+  int one32th = totalTime_ms / 32;
+  rgbFlash(4*one32th);  // 1/2 length * 1/4 rgb = 1/8  = 4*1/32
+  rgbFlash(2*one32th);  // 1/4 length * 1/4 rgb = 1/16 = 2*1/32
+  rgbFlash(  one32th);  // 1/8 length * 1/4 rgb = 1/32 =   1/32
+  gradientPulseSetup(WHITE,OFF, one32th*4000); // 1/8th length = 4*1/32; convert to seconds
+}
+
+
 void toggleDebug() {
   debugMode = !debugMode;
   Serial.print("Debug mode ");
@@ -473,3 +498,13 @@
     recipient[x]=donor[x];
   }
 }
+
+boolean redundantFlashCommand(const int col1[], const int col2[], int fTime) {
+  for (int x=0; x<3; x++) {
+    if (flashcol1[x]!=col1[x]) {return false;}
+    if (flashcol2[x]!=col2[x]) {return false;}
+  }
+  if (flashTimePerColor_ms != fTime) {return false;}
+  return true;
+}
+


RearPanel external ant (#110)

RearPanel external ant (#110)

--- Photon/Controllers/RearPanel/src/RearPanel.ino
+++ Photon/Controllers/RearPanel/src/RearPanel.ino
@@ -70,6 +70,7 @@
 int sleeping = 0;

 void setup() {
+    WiFi.selectAntenna(ANT_EXTERNAL);
     IoT::begin("192.168.50.33", "RearPanel");
     createDevices();
     handleDaylightSavings();


forgot a break statement

forgot a break statement

--- marsduino/marsduino.ino
+++ marsduino/marsduino.ino
@@ -190,19 +190,20 @@
         char ledValue = codeArray[1];
         int ledDutyCycle = int(charToInt(ledValue) * 25.5);
         analogWrite(ledPin, ledDutyCycle); //sets up PWM on the speedPin
-        logs = "LEDs set to level to " + ledValue;
+        logs = "LEDs set to level to " + String(ledValue);
         break;
       }

     case 'R': {/*reference voltage reset*/
       useRef = true;
       realReference = input.substring(1).toInt();
-      logs = "Voltage Reference set to " + input.substring(1);
+      logs = "Voltage Reference set to " + String(input.substring(1));
       break;
     }
     case 'E': {/*reference voltage disabled*/
       useRef = false;
       logs = "Voltage Reference disabled";
+      break;
     }
     case 'W': {/*watchdog timer reset*/
       watchdogEnabled = true;
@@ -213,6 +214,7 @@
     case 'Q': {/*watchdog timer disabled*/
       watchdogEnabled = false;
       logs = "Watchdog Timer Disabled";
+      break;
     }
     case 'C': { /*memory mode enabled*/
       memCheck = true;


ardu file update

ardu file update

--- Room_System_Ardu/Room_System_Ardu.ino
+++ Room_System_Ardu/Room_System_Ardu.ino
@@ -1,6 +1,6 @@
 #include <FastLED.h>

-#define LED_PIN     3
+#define LED_PIN     11
 #define NUM_LEDS    150
 #define BRIGHTNESS  64
 #define LED_TYPE    WS2811
@@ -41,27 +41,29 @@
   Lights_ON = not digitalRead(Lights_Pin);
   Flashing_Lights = not digitalRead(Flash_Pin);
   Brightness = analogRead(Brightness_Pot);
-//  if (Flashing_Lights) {
-//    digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
-//    delay(1000);              // wait for a second
-//    digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
-//    delay(1000);              // wait for a second
-//    Serial.print("Flash");
-//  }
-  if (Lights_ON) {
-//if (true){
+  Brightness = map(Brightness,0,1023,0,255);
+  //  if (Flashing_Lights) {
+  //    digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
+  //    delay(1000);              // wait for a second
+  //    digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
+  //    delay(1000);              // wait for a second
+  //    Serial.print("Flash");
+  //  }
+  //  if (Lights_ON) {
+  if (true) {
     digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
-//    delay(500);              // wait for a second
-//    digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
-//    delay(500);
-//    Serial.print("Light");
+    //    delay(500);              // wait for a second
+    //    digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
+    //    delay(500);
+    //    Serial.print("Light");

     ChangePalettePeriodically();

     static uint8_t startIndex = 0;
     startIndex = startIndex + 1; /* motion speed */

-    FillLEDsFromPaletteColors( startIndex);
+    FillLEDsFromPaletteColors(startIndex, (int) Brightness);
+

     FastLED.show();
     FastLED.delay(1000 / UPDATES_PER_SECOND);
@@ -73,15 +75,15 @@
     //    Serial.print("OFF");
   }
   Serial.print(Flashing_Lights);
-  //  Serial.println(Brightness);
+  Serial.println(Brightness);
   Serial.println(Lights_ON);
 }

-void FillLEDsFromPaletteColors( uint8_t colorIndex)
-{
-  uint8_t brightness = 255;
+void FillLEDsFromPaletteColors( uint8_t colorIndex, uint8_t brightness)
+{
+//    uint8_t brightness = 255;

   for ( int i = 0; i < NUM_LEDS; i++) {
     leds[i] = ColorFromPalette( currentPalette, colorIndex, brightness, currentBlending);


Don't get too attached .. this code is not long for the world.

git-svn-id: d8bfcd070c2c81762cca1b3912331324182919ba@16736 0d6f1817-ed0e-0410-87c9-987e46238f29

--- zimodem/proto_zmodem.ino
+++ zimodem/proto_zmodem.ino
@@ -30,7 +30,6 @@
  *  Jacques Mattheij
  ******************************************************************************/

-=======
 #ifdef INCLUDE_SD_SHELL
 /*
  * zmodem primitives and other code common to zmtx and zmrx


Update multiple_animations.ino

Update multiple_animations.ino

minor clarification in a comment line

--- multiple_animations.ino
+++ multiple_animations.ino
@@ -37,8 +37,8 @@
 #define NUM_LEDS (numA + numB + numC + numD)

-CRGB leds[NUM_LEDS];  //what actually gets displayed
-CRGB ledsA[numA];     //numA thru numD are "working" arrays
+CRGB leds[NUM_LEDS];  // The array that actually gets displayed
+CRGB ledsA[numA];     // ledsA thru ledsD are "working" arrays
 CRGB ledsB[numB];
 CRGB ledsC[numC];
 CRGB ledsD[numD];


Rename pinEn -> EN_PIN and pinStep -> STEP_PIN

--- examples/TMC2130_live_tune/TMC2130_live_tune.ino
+++ examples/TMC2130_live_tune/TMC2130_live_tune.ino
@@ -9,7 +9,7 @@
 float hold_x = 0.5;

 #include <TMC2130Stepper.h>
-TMC2130Stepper myStepper = TMC2130Stepper(pinEN, pinDIR, pinStep, pinCS);
+TMC2130Stepper myStepper = TMC2130Stepper(EN_PIN, DIR_PIN, STEP_PIN, CS_PIN);

 void serialTuple(String cmd, int arg) {
 	Serial.print("Received command: ");
@@ -24,7 +24,7 @@
 	Serial.begin(9600);
 	myStepper.begin();
 	myStepper.SilentStepStick2130(1000);
-	digitalWrite(pinEN, LOW);
+	digitalWrite(EN_PIN, LOW);
 	Serial.println("Setup ready");
 }

@@ -38,6 +38,7 @@
 		if (cmd == "run") {
 			serialTuple("run", arg);
 			running = arg;
+			arg ? digitalWrite(EN_PIN, LOW) : digitalWrite(EN_PIN, HIGH);
 		}
 		else if (cmd == "speed") {
 			serialTuple("speed", arg);
@@ -330,9 +331,9 @@
 		}
 	}
 	if (running) {
-		digitalWrite(pinStep, HIGH);
+		digitalWrite(STEP_PIN, HIGH);
 		delayMicroseconds(speed);
-		digitalWrite(pinStep, LOW);
+		digitalWrite(STEP_PIN, LOW);
 		delayMicroseconds(speed);
 	}
 }


attempt to fix the omoplate thumb issue on uno

--- src/resource/Arduino/MRLComm.ino
+++ src/resource/Arduino/MRLComm.ino
@@ -16,29 +16,10 @@
 *
 */

-#ifndef MRLComm_h
-#define MRLComm_h
+// #ifndef MRLComm_h
+// #define MRLComm_h

 #include "Servo.h"
-
-#include <inttypes.h>
-#include <avr/io.h>
-
-#include <inttypes.h>
-
-#if defined(ARDUINO) && ARDUINO >= 100
-#include "Arduino.h"	// for digitalRead, digitalWrite, etc
-#else
-#include "WProgram.h"
-#endif
-
-// Normally Servo.h must be included before Firmata.h (which then includes
-// this file).  If Servo.h wasn't included, this allows the code to still
-// compile, but without support for any Servos.  Hopefully that's what the
-// user intended by not including Servo.h
-#ifndef MAX_SERVOS
-#define MAX_SERVOS 0
-#endif

 // ----------  MRLCOMM FUNCTION INTERFACE BEGIN -----------
 #define MRLCOMM_VERSION				19
@@ -327,27 +308,9 @@
 	bool blinkState;
 };

-#endif
-/*==================== MRLCOMM.H END ====================*/
+// #endif
+/*==================== MRLCOMM.H END ========================*/
 /*==================== MRLCOMM.CPP BEGIN ====================*/
-/**
-*
-* @author GroG (at) myrobotlab.org
-*
-* This file is part of MyRobotLab.
-*
-* Enjoy !
-*
-* MRLComm Library
-* -----------------
-* Purpose: support servos, sensors, analog & digital polling
-* oscope, motors, range sensors, pingdar & steppers.
-*
-* Requirements: MyRobotLab running on a computer & a serial connection
-*
-*/
-
-// FIXED BY MOVING UP #include "Servo.h"
 // FIXME #include <MRLComm.h>

 MRLComm::MRLComm(){


Changed tft/touch refresh/scan rate in menu to UPDATE_FREQ_TFT.

--- tfttask.ino
+++ tfttask.ino
@@ -103,17 +103,16 @@
     {
       case normal:
         showStatus();
-        vTaskDelay( tftTaskdelayTime );
         break;

       case menu:
         showMenu();
-        vTaskDelay( 10 / portTICK_PERIOD_MS );
         break;

       default:
         break;
     }
+    vTaskDelay( tftTaskdelayTime );
   }
 }


Removes #defines for constants and code control, addresses issue #6.

--- Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
+++ Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
@@ -37,13 +37,13 @@
 #include <std_msgs/String.h>

 // Teensy pin definitions
-#define BLINK_PIN           13  // Teensy digital pin 13
-#define ENCODER_LEFT_PIN_1  29  // Teensy digital pin 29
-#define ENCODER_LEFT_PIN_2  30  // Teensy digital pin 30
-#define ENCODER_RIGHT_PIN_1 31  // Teensy digital pin 31
-#define ENCODER_RIGHT_PIN_2 32  // Teensy digital pin 32
-#define BUMPER_LEFT_PIN     A15 // Teensy analog pin 15
-#define BUMPER_RIGHT_PIN    A14 // Teensy analog pin 14
+const int BLINK_PIN(13);           // Teensy digital pin 13
+const int ENCODER_LEFT_PIN_1(29);  // Teensy digital pin 29
+const int ENCODER_LEFT_PIN_2(30);  // Teensy digital pin 30
+const int ENCODER_RIGHT_PIN_1(31); // Teensy digital pin 31
+const int ENCODER_RIGHT_PIN_2(32); // Teensy digital pin 32
+const int BUMPER_LEFT_PIN(A15);    // Teensy analog pin 15
+const int BUMPER_RIGHT_PIN(A14);   // Teensy analog pin 14

 // Timer
 Timer timer;
@@ -54,10 +54,10 @@
 double motor_right_speed;

 // Victoria constants
-#define TICKS_PER_RADIAN 9072 // TODO(mwomack): Verify real value
-#define TRACK_RADIUS 0.235  // in meters
-#define WHEEL_RADIUS 0.127  // in meters
-#define MAX_SPEED 4.71      // in meters/second
+const unsigned long TICKS_PER_RADIAN(9072); // TODO(mwomack): Verify real value
+const double TRACK_RADIUS(0.235);  // in meters
+const double WHEEL_RADIUS(0.127);  // in meters
+const double MAX_SPEED(4.71);      // in meters/second

 // Bumper sensors
 bool bumper_stop = false; // Set to true if bumpers indicate robot should stop
@@ -71,7 +71,7 @@
 unsigned long encoder_right_pos;
 ros::Time last_encoder_read_time;

-#define NUM_VEL_SAMPLES 10
+const int NUM_VEL_SAMPLES(10);
 double ang_v_samples_l[NUM_VEL_SAMPLES];
 double ang_v_samples_r[NUM_VEL_SAMPLES];
 int velocity_index = 0;
@@ -88,7 +88,7 @@
 // ROS cmd_vel subscriber
 // Threshold, in seconds, to wait for a cmd_vel message else take action
 // to stop robot activity
-#define CMD_VEL_TIMEOUT_THRESHOLD 0.2 // 200 milliseconds
+const double CMD_VEL_TIMEOUT_THRESHOLD(0.2); // 200 milliseconds
 ros::Time last_cmd_vel_time;
 bool cmd_vel_timeout_stop = false; // Set to true if time out threshold has been exceeded
 void cmdVelCallback(const geometry_msgs::Twist& twist_msg);
@@ -111,39 +111,17 @@
 char ros_odom_header_frame_id[] = "/odom";
 char ros_odom_child_frame_id[] = "/base_link";

-// ROS Debug publishers
-#define ENABLE_BUMPER_DEBUG  // Uncomment to publish bumper debug info
-#define ENABLE_ENCODER_DEBUG  // Uncomment to publish encoder debug info
-#define ENABLE_IMU_DEBUG  // Uncomment to publish imu debug info
-#define ENABLE_MAGNETOMETER_DEBUG  // Uncomment to publish magnetometer debug info
-#define ENABLE_TEENSY_DEBUG  // Uncomment to publish teensy debug info
-
 char debug_str[80];
 std_msgs::String ros_debug_msg;

-#ifdef ENABLE_BUMPER_DEBUG
 ros::Publisher ros_bumper_debug_pub("bumper_debug", &ros_debug_msg);
-#endif
-
-#ifdef ENABLE_ENCODER_DEBUG
 ros::Publisher ros_encoder_debug_pub("encoder_debug", &ros_debug_msg);
-#endif
-
-#ifdef ENABLE_IMU_DEBUG
 ros::Publisher ros_imu_debug_pub("imu_debug", &ros_debug_msg);
-#endif
-
-#ifdef ENABLE_MAGNETOMETER_DEBUG
 ros::Publisher ros_magnetometer_debug_pub("magnetometer_debug", &ros_debug_msg);
-#endif
-
-#ifdef ENABLE_TEENSY_DEBUG
-ros::Publisher ros_teensy_debug_pub("teensy_debug_info", &ros_debug_msg);
-#endif

 // Debug blink
 // Blink duration is in milliseconds.
-#define BLINK_DURATION 500
+const int BLINK_DURATION(500);
 int blink_state = LOW;

 void setup() {
@@ -208,6 +186,26 @@
   if (!ros_nh.getParam("publish_magnetometer_freq_hz", &publish_magnetometer_freq_hz)) {
     publish_magnetometer_freq_hz = 2;
   }
+
+  int publish_bumper_debug_info_freq_hz;
+  if (!ros_nh.getParam("publish_bumper_debug_info_freq_hz", &publish_bumper_debug_info_freq_hz)) {
+    publish_bumper_debug_info_freq_hz = 10;
+  }
+
+  int publish_encoder_debug_info_freq_hz;
+  if (!ros_nh.getParam("publish_encoder_debug_info_freq_hz", &publish_encoder_debug_info_freq_hz)) {
+    publish_encoder_debug_info_freq_hz = 10;
+  }
+
+  int publish_imu_debug_info_freq_hz;
+  if (!ros_nh.getParam("publish_imu_debug_info_freq_hz", &publish_imu_debug_info_freq_hz)) {
+    publish_imu_debug_info_freq_hz = 2;
+  }
+
+  int publish_magnetometer_debug_info_freq_hz;
+  if (!ros_nh.getParam("publish_magnetometer_debug_info_freq_hz", &publish_magnetometer_debug_info_freq_hz)) {
+    publish_magnetometer_debug_info_freq_hz = 2;
+  }

   // Initialize broadcasters
   ros_odom_transform.header.frame_id = ros_odom_header_frame_id;
@@ -223,10 +221,10 @@
   ros_nh.subscribe(ros_cmd_vel_sub);

   // Setup Timer callbacks
-  timer.every((1.0/read_encoders_freq_hz) * 1000, doReadEncoders);
-  timer.every((1.0/publish_odom_freq_hz) * 1000, doPublishOdom);
-  timer.every((1.0/publish_imu_freq_hz) * 1000, doPublishImu);
-  timer.every((1.0/publish_magnetometer_freq_hz) * 1000, doPublishMagnetometer);
+  timer.every(convertFreqToMillis(read_encoders_freq_hz), doReadEncoders);
+  timer.every(convertFreqToMillis(publish_odom_freq_hz), doPublishOdom);
+  timer.every(convertFreqToMillis(publish_imu_freq_hz), doPublishImu);
+  timer.every(convertFreqToMillis(publish_magnetometer_freq_hz), doPublishMagnetometer);
   timer.every(BLINK_DURATION, doBlink);

   ros::Time current_time = ros_nh.now();
@@ -235,25 +233,14 @@
   last_encoder_read_time = current_time;

   // Initialize ros debug publishers
-#ifdef ENABLE_BUMPER_DEBUG
   ros_nh.advertise(ros_bumper_debug_pub);
-  timer.every(500, doBumperDebug);
-#endif
-#ifdef ENABLE_ENCODER_DEBUG
   ros_nh.advertise(ros_encoder_debug_pub);
-  timer.every(500, doEncoderDebug);
-#endif
-#ifdef ENABLE_IMU_DEBUG
   ros_nh.advertise(ros_imu_debug_pub);
-  timer.every(500, doImuDebug);
-#endif
-#ifdef ENABLE_MAGNETOMETER_DEBUG
   ros_nh.advertise(ros_magnetometer_debug_pub);
-  timer.every(500, doMagnetometerDebug);
-#endif
-#ifdef ENABLE_TEENSY_DEBUG
-  ros_nh.advertise(ros_teensy_debug_pub);
-#endif
+  timer.every(convertFreqToMillis(publish_bumper_debug_info_freq_hz), doBumperDebug);
+  timer.every(convertFreqToMillis(publish_encoder_debug_info_freq_hz), doEncoderDebug);
+  timer.every(convertFreqToMillis(publish_imu_debug_info_freq_hz), doImuDebug);
+  timer.every(convertFreqToMillis(publish_magnetometer_debug_info_freq_hz), doMagnetometerDebug);
 }

 void loop() {
@@ -460,7 +447,6 @@
   digitalWrite(BLINK_PIN, blink_state);
 }

-#ifdef ENABLE_BUMPER_DEBUG
 void doBumperDebug() {
   // Read the bumper sensors
   snprintf(debug_str, sizeof(debug_str),
@@ -468,9 +454,7 @@
   ros_debug_msg.data = debug_str;
   ros_bumper_debug_pub.publish(&ros_debug_msg);
 }
-#endif
-
-#ifdef ENABLE_ENCODER_DEBUG
+
 void doEncoderDebug() {
   // Read the encoders
   snprintf(debug_str, sizeof(debug_str), "L: %ld    R: %ld",
@@ -478,9 +462,7 @@
   ros_debug_msg.data = debug_str;
   ros_encoder_debug_pub.publish(&ros_debug_msg);
 }
-#endif
-
-#ifdef ENABLE_IMU_DEBUG
+
 void doImuDebug() {
   // Read the IMU
   if (imu_err) {
@@ -496,9 +478,7 @@
   }
   ros_imu_debug_pub.publish(&ros_debug_msg);
 }
-#endif
-
-#ifdef ENABLE_MAGNETOMETER_DEBUG
+
 void doMagnetometerDebug() {
   // Read the Magnetometer
   if (mag_err) {
@@ -513,4 +493,14 @@
   }
   ros_magnetometer_debug_pub.publish(&ros_debug_msg);
 }
-#endif
+
+/*
+ * Converts a frequency in hertz to the
+ * number of milliseconds to match the
+ * frequency. For example, 2 hz = 500 millis
+ * or 100 hz = 10 millis.
+ */
+int convertFreqToMillis(int frequency) {
+  return static_cast<int>((1.0/frequency) * 1000);
+}
+


Add Change_Baud_Rate Example

Add Change_Baud_Rate Example


Removed debug lines

Removed debug lines

--- arduino/PanelInterface/PanelInterface.ino
+++ arduino/PanelInterface/PanelInterface.ino
@@ -146,11 +146,10 @@
 void do_panel_set(uint8_t strip, uint8_t panel, uint8_t intensity, const CRGB &color, AnywareEasing::EasingType  easing)
 {
   CRGB newcol = applyIntensity(color, intensity);
-  Serial.print(strip);Serial.print(" ");Serial.println(panel);
+
   const Pair &p = LEDStripInterface::mapToLED(strip, panel);
   if (p.stripid < 0 || p.pixelid < 0) {
     printError(F("client error"), F("Strip or panel out of range"));
-    Serial.print(p.stripid);Serial.print(" ");Serial.println(p.pixelid);
     return;
   }
   LEDStripInterface &s = LEDStripInterface::getStrip(p.stripid);


Fix a problem with a compilation on Microsoft Windows

Signed-off-by: Roman3349 <6b7cbc66756660b4790b3af1ec1507653acaa035@centrum.cz>

--- src/Blink.ino
+++ src/Blink.ino
@@ -0,0 +1,401 @@
+/**
+ * Copyright 2015-2016 MICRORISC s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stddef.h>
+#include <stdint.h>
+#include <dpa_library.h>
+#if defined(__PIC32MX__)
+#include <WProgram.h>
+#else
+#include <Arduino.h>
+#endif
+#if defined(__AVR__) || defined(CORE_TEENSY)
+#include <MsTimer2.h>
+#include <TimerOne.h>
+#elif defined(__SAM3X8E__)
+#include <DueTimer.h>
+#endif
+#if defined(__SPI_INTERFACE__)
+#include <SPI.h>
+#endif
+
+/*
+ * C prototypes
+ */
+#if defined(__SPI_INTERFACE__)
+extern "C" void DPA_DeselectTRmodule();
+extern "C" uint8_t DPA_SendSpiByte(uint8_t txByte);
+#elif defined(__UART_INTERFACE__)
+extern "C" void DPA_SendUartByte(uint8_t txByte);
+#endif
+
+/*
+ * C++ prototypes
+ */
+void setup();
+void loop();
+void greenLed(uint16_t addr, uint8_t cmd);
+void redLed(uint16_t addr, uint8_t cmd);
+void dpaRequests();
+void dpaAnswerHandler(T_DPA_PACKET *dpaAnswerPacket);
+void dpaTimeoutHandler();
+void swTimeoutHandler();
+void msTimerCallback();
+#if defined(TR7xD)
+void usTimerCallback();
+#endif
+#if defined(__PIC32MX__)
+uint32_t msTimerCallbackPic32(uint32_t currentTime);
+#if defined(TR7xD)
+uint32_t usTimerCallbackPic32(uint32_t currentTime);
+#endif
+#endif
+
+/*
+ * Addresses
+ */
+#define COORDINATOR 0
+#define NODE1       1
+#define NODE2       2
+#define NODE3       3
+#define NODE4       4
+#define NODE5       5
+#define LOCAL       0xFC
+
+/*
+ * Message types
+ */
+
+#define CONFIRMATION  1
+#define RESPONSE      2
+
+/*
+ * Statuses
+ */
+#define NO_WAITING            0
+#define CONFIRMATION_WAITING  1
+#define RESPONSE_WAITING      2
+
+/*
+ * Variables
+ */
+#if defined(__SPI_INTERFACE__)
+/// SPI SS (Slave select) pin of IQRF DCTR module
+uint8_t iqrfSs = 10;
+#endif
+/// User timer period in ms
+uint16_t userTimerPeriod = 1000; // 1000@1ms = 1s
+
+typedef enum {
+    GLED_PULSE,
+    RLED_PULSE
+} DPA_RQ;
+
+typedef struct {
+    // Timer
+    volatile uint16_t swTimer;
+    volatile bool swTimerAck;
+    volatile uint8_t ticks;
+#if defined(__SPI_INTERFACE__) && defined(TR7xD)
+    // SPI
+    bool TRmoduleSelected;
+#endif
+    // DPA
+    volatile uint16_t dpaTimeoutCnt;
+    uint16_t dpaStep;
+    uint8_t state;
+    T_DPA_PACKET myDpaRequest;
+    DPA_RQ cmds;
+} app_vars_t;
+app_vars_t app_vars;
+
+/**
+ * Init peripherals
+ */
+void setup() {
+    Serial.begin(9600);
+#if defined(__UART_INTERFACE__)
+    Serial1.begin(115200);
+#elif defined(__SPI_INTERFACE__)
+    pinMode(iqrfSs, OUTPUT);
+    digitalWrite(iqrfSs, HIGH);
+    SPI.begin();
+#endif
+#if defined(__AVR__) || defined(CORE_TEENSY)
+    MsTimer2::set(1, msTimerCallback);
+    MsTimer2::start();
+#if defined(TR7xD)
+    Timer1.initialize(150);
+    Timer1.attachInterrupt(usTimerCallback);
+#endif
+#elif defined(__SAM3X8E__)
+    Timer6.attachInterrupt(msTimerCallback).start(1000);
+#if defined(TR7xD)
+    Timer7.attachInterrupt(usTimerCallback).start(150);
+#endif
+#elif defined(__PIC32MX__)
+    attachCoreTimerService(msTimerCallbackPic32);
+#if defined(TR7xD)
+    attachCoreTimerService(usTimerCallbackPic32);
+#endif
+#endif
+    // Clear local variable
+    memset(&app_vars, 0, sizeof (app_vars_t));
+    app_vars.swTimer = userTimerPeriod;
+    app_vars.state = 1;
+    // DPA library initialization
+    DPA_Init();
+    // Set DPA response handler
+    DPA_SetAnswerHandler(dpaAnswerHandler);
+    // Wait 1s
+    delay(1000);
+    Serial.println("Peripheral and DPA init done");
+}
+
+/**
+ * Main loop
+ */
+void loop() {
+#if defined(__UART_INTERFACE__)
+    // Check and read data from UART
+    DPA_ReadUartByte();
+#endif
+    // Sending DPA requests
+    if (app_vars.swTimerAck) {
+        // Function for sending DPA requests over SPI/UART
+        dpaRequests();
+        app_vars.swTimerAck = false;
+    }
+    // Run DPA library handler
+    DPA_LibraryDriver();
+}
+
+/**
+ * DPA request to drive green LED peripheral
+ * @param addr Address
+ * &param cmd Command
+ */
+void greenLed(uint16_t addr, uint8_t cmd) {
+    app_vars.myDpaRequest.NADR = addr;
+    app_vars.myDpaRequest.PNUM = PNUM_LEDG;
+    app_vars.myDpaRequest.PCMD = cmd;
+    app_vars.myDpaRequest.HWPID = HWPID_DoNotCheck; // replace HW_PROFILE_DO_NOT_CHECK
+    // Initial timeout 1s for either confirmation or response
+    app_vars.dpaTimeoutCnt = 1000;
+    DPA_SendRequest(&app_vars.myDpaRequest, 0);
+}
+
+/**
+ * DPA request to drive red LED peripheral
+ * @param addr Address
+ * &param cmd Command
+ */
+void redLed(uint16_t addr, uint8_t cmd) {
+    app_vars.myDpaRequest.NADR = addr;
+    app_vars.myDpaRequest.PNUM = PNUM_LEDR;
+    app_vars.myDpaRequest.PCMD = cmd;
+    app_vars.myDpaRequest.HWPID = HWPID_DoNotCheck; // replace HW_PROFILE_DO_NOT_CHECK
+    // Initial timeout 1s for either confirmation or response
+    app_vars.dpaTimeoutCnt = 1000;
+    DPA_SendRequest(&app_vars.myDpaRequest, 0);
+}
+
+/**
+ * Send DPA requests
+ */
+void dpaRequests() {
+    // if DPA library is busy, or dpa operation in progress, then return
+    if (DPA_GetStatus() != DPA_READY || app_vars.dpaStep != NO_WAITING) {
+        return;
+    }
+    // 100ms before sending another request
+    app_vars.ticks = 100;
+    while (app_vars.ticks) {
+    }
+    switch (app_vars.state) {
+    case 1:
+        redLed(COORDINATOR, CMD_LED_PULSE);
+        Serial.println("LEDR pulse");
+        app_vars.state = 2;
+        break;
+    case 2:
+        greenLed(NODE1, CMD_LED_PULSE);
+        Serial.println("LEDG pulse");
+        app_vars.state = 1;
+        break;
+    }
+    if (app_vars.myDpaRequest.NADR == 0x00 || app_vars.myDpaRequest.NADR == 0xFC) {
+        // DPA answer would be response
+        app_vars.dpaStep = RESPONSE_WAITING;
+    } else {
+        // DPA answer would be confirmation
+        app_vars.dpaStep = CONFIRMATION_WAITING;
+    }
+}
+
+/**
+ * DPA answer handler
+ * @param dpaAnswerPacket Pointer to DPA answer packet
+ */
+void dpaAnswerHandler(T_DPA_PACKET *dpaAnswerPacket) {
+    if (app_vars.dpaStep == CONFIRMATION_WAITING &&
+            dpaAnswerPacket->ResponseCode == STATUS_CONFIRMATION) {
+        app_vars.dpaStep = RESPONSE_WAITING;
+        app_vars.dpaTimeoutCnt = DPA_GetEstimatedTimeout();
+        return;
+    }
+    if (app_vars.dpaStep == RESPONSE_WAITING &&
+            dpaAnswerPacket->ResponseCode == STATUS_NO_ERROR) {
+        app_vars.dpaStep = NO_WAITING;
+        app_vars.dpaTimeoutCnt = 0;
+        // ANY USER CODE FOR DPA RESPONSE PROCESSING
+        return;
+    }
+    // ANY USER CODE FOR ASYNCHRONOUS DPA MESSAGES PROCESSING
+}
+
+/**
+ * DPA response timeout handler
+ */
+void dpaTimeoutHandler() {
+    app_vars.dpaStep = NO_WAITING;
+    // ANY USER CODE FOR OPERATION TIMEOUT HANDLING
+}
+
+/**
+ * User timeout handler
+ */
+void swTimeoutHandler() {
+    app_vars.swTimerAck = true;
+}
+
+/**
+ * 1ms timer callback
+ */
+void msTimerCallback() {
+#if defined(TR5xD)
+    DPA_SetTimmingFlag();
+#endif
+    // Timeout handler
+    if (app_vars.dpaTimeoutCnt) {
+        if ((--app_vars.dpaTimeoutCnt) == 0) {
+            // If timeout is expired it call timeout handler
+            dpaTimeoutHandler();
+        }
+    }
+    // SW timer, call timeout handler
+    if (app_vars.swTimer) {
+        if ((--app_vars.swTimer) == 0) {
+            swTimeoutHandler();
+            app_vars.swTimer = userTimerPeriod;
+        }
+    }
+    // Delay timer
+    if (app_vars.ticks) {
+        --app_vars.ticks;
+    }
+}
+
+/**
+ * 150us timer callback for DCTR-7x modules
+ */
+void usTimerCallback() {
+    DPA_SetTimmingFlag();
+}
+
+#if defined(__PIC32MX__)
+
+/**
+ * 1ms timer callback
+ * @param currentTime Current time
+ * @return Next time
+ */
+uint32_t msTimerCallbackPic32(uint32_t currentTime) {
+    msTimerCallback();
+    return (currentTime + CORE_TICK_RATE);
+}
+#if defined(TR7xD)
+
+/**
+ * 150us timer callback for DCTR-7x modules
+ * @param currentTime Current time
+ * @return Next time
+ */
+uint32_t usTimerCallbackPic32(uint32_t currentTime) {
+    usTimerCallback();
+    return (currentTime + CORE_TICK_RATE);
+}
+#endif
+#endif
+
+#if defined(__SPI_INTERFACE__)
+
+/**
+ * DPA SPI deselect module
+ */
+void DPA_DeselectTRmodule() {
+#if defined(TR7xD)
+    app_vars.TRmoduleSelected = false;
+#endif
+    pinMode(iqrfSs, OUTPUT);
+    digitalWrite(iqrfSs, HIGH);
+}
+
+/**
+ * Send DPA byte over SPI
+ * @param txByte Byte to send
+ * @return Received byte
+ */
+uint8_t DPA_SendSpiByte(uint8_t txByte) {
+#if defined(TR7xD)
+    if (!app_vars.TRmoduleSelected) {
+        app_vars.TRmoduleSelected = true;
+        digitalWrite(iqrfSs, LOW);
+        delayMicroseconds(15);
+    }
+#else
+    digitalWrite(iqrfSs, LOW);
+    delayMicroseconds(15);
+#endif
+    SPI.beginTransaction(SPISettings(250000, MSBFIRST, SPI_MODE0));
+    uint8_t rxByte = SPI.transfer(txByte);
+    SPI.endTransaction();
+    delayMicroseconds(15);
+    DPA_DeselectTRmodule();
+    return rxByte;
+}
+#elif defined(__UART_INTERFACE__)
+
+/**
+ * Send DPA byte over UART
+ * @param txByte Byte to send
+ */
+void DPA_SendUartByte(uint8_t txByte) {
+    Serial1.write(txByte);
+}
+
+/**
+ * Read DPA byte from UART
+ */
+void DPA_ReadUartByte() {
+    while (Serial1.available()) {
+        // Read received byte
+        uint8_t rxByte = Serial1.read();
+        // Load that byte to DPA library
+        DPA_ReceiveUartByte(rxByte);
+    }
+}
+#endif


[lmr] Switch pins to match HeaterMeter pinouts

--- arduino/lmremote/lmremote.ino
+++ arduino/lmremote/lmremote.ino
@@ -15,24 +15,24 @@
 const char _rfNodeBaseId = 0;
 // RFM12B band RF12_433MHZ, RF12_868MHZ, RF12_915MHZ
 const unsigned char _rfBand = RF12_915MHZ;
-// How many seconds to delay between measurements
+// How many seconds to delay between temperature measurements
 const unsigned char _sleepInterval = 2;
-// Analog pins to read. This is a bitfield, LSB is analog 0
+// Analog pins to read. This is a bitfield, LSB is analog 5
 const unsigned char _enabledProbePins = 0x01;
 // Analog pin connected to source power.  Set to 0xff to disable sampling
 const unsigned char _pinBattery = 0xff;
 // Digital pins for LEDs, 0xff to disable
 const unsigned char _pinLedRx = 0xff;
 const unsigned char _pinLedTx = 0xff;
-const unsigned char _pinLedRxSearch = 0xff;
-const unsigned char _pinLedRxConverge = 6;
-const unsigned char _pinLedRxLocked = 7;
+const unsigned char _pinLedRxSearch = 4;   // ATmega pin 6
+const unsigned char _pinLedRxConverge = 5; // ATmega pin 11
+const unsigned char _pinLedRxLocked = 9;   // ATmega pin 15
 // Digital pin used for sourcing power to the probe dividers
-const unsigned char _pinProbeSupply = 4;
+const unsigned char _pinProbeSupply = 7;   // ATmega pin 13
 // Digital pin used for fan output, must support PWM, 0xff to disable
-const unsigned char _pinOutputFan = 5;
+const unsigned char _pinOutputFan = 3;     // ATmega pin 5
 // Digital pin used for servo output, 0xff to disable
-const unsigned char _pinOutputServo = 8;
+const unsigned char _pinOutputServo = 8;   // ATmega pin 14
 // Percentage (integer) of VCC where the battery is considered low (33% = 1.1V)
 #define BATTERY_LOW_PCT 33
 // Number of seconds to keep the "recent/new" bit set
@@ -226,7 +226,7 @@
 {
 #if defined(LMREMOTE_SERIAL) && defined(_DEBUG)
   Serial.print(millis(), DEC);
-  Serial.print(F("rfSetRecvState ")); Serial.println(state, DEC);
+  Serial.print(F(" rfSetRecvState ")); Serial.println(state, DEC);
 #endif
   _recvState = state;

@@ -451,7 +451,8 @@

     for (unsigned char o=0; o<OVERSAMPLE_COUNT[TEMP_OVERSAMPLE_BITS]; ++o)
     {
-      unsigned int adc = analogReadSleep(pin);
+      // 'Pins' 0-5 are actually wired starting at A5 down to A0
+      unsigned int adc = analogReadSleep(5 - pin);
       if (adc == 0 || adc >= 1023)
       {
         oversampled_adc = 0;


inversed directions for forward and backward

--- arduino/pi_rover/pi_rover.ino
+++ arduino/pi_rover/pi_rover.ino
@@ -173,9 +173,9 @@

 String lookDirection(int argument) {
   String result;
-
+
   Serial.print("arg: " +String(argument)+ "\n");
-
+
   if (argument >= 0 && argument <= 180) {

     digitalWrite(ledPin, HIGH);
@@ -221,29 +221,29 @@

   turnMotorsOn();

+  motor1.run(FORWARD);
+  motor2.run(FORWARD);
+  motor3.run(BACKWARD);
+  motor4.run(BACKWARD);
+
+  return "ok";
+}
+
+String backward(int speedInPercentage)
+{
+  if (speedInPercentage > 0)
+  {
+    setMotorSpeed(speedInPercentage);
+  }
+
+  isMovingBackward = true;
+
+  turnMotorsOn();
+
   motor1.run(BACKWARD);
   motor2.run(BACKWARD);
   motor3.run(FORWARD);
   motor4.run(FORWARD);
-
-  return "ok";
-}
-
-String backward(int speedInPercentage)
-{
-  if (speedInPercentage > 0)
-  {
-    setMotorSpeed(speedInPercentage);
-  }
-
-  isMovingBackward = true;
-
-  turnMotorsOn();
-
-  motor1.run(FORWARD);
-  motor2.run(FORWARD);
-  motor3.run(BACKWARD);
-  motor4.run(BACKWARD);

   return "ok";
 }


removed obsolete functions

removed obsolete functions

--- arduino/light_switch/light_switch.ino
+++ arduino/light_switch/light_switch.ino
@@ -113,34 +113,6 @@
   return (char)(((int)'0') + button_number);
 }

-int api_available()
-{
-  set_headers();
-  int status_code = client.get( "/rest" );
-  if ( status_code == 200 )
-  { return 1; }
-  else
-  { return 0; }
-}
-
-int more_than_4000_millis_passed()
-{
-  unsigned long current_millis = millis();
-  if ( current_millis >= last_millis  )
-  {
-    if ( current_millis - last_millis > 4000 )
-    {
-      last_millis = current_millis;
-      return 1;
-    }
-  }
-  else
-  {
-    last_millis = current_millis;
-  }
-  return 0;
-}
-
 void sturtup_blink()
 {
   for (int i=0; i<30; i++) {


Use prometheus client to send messages.

Use prometheus client to send messages.

--- octotemp/code/OctoTemp/OctoTemp/OctoTemp.ino
+++ octotemp/code/OctoTemp/OctoTemp/OctoTemp.ino
@@ -1,8 +1,12 @@
 #include <Math.h>
 #include <Wire.h>
+#include <prometheus.h>

 #define SDAPIN 13
 #define SCLPIN 12
+
+#define SERVER_IP           "10.1.20.200"
+#define SERVER_PORT         9091

 // TODO(z2amiller):  Set up interrupts to call back when the temperature
 //                   on one of the pins gets too hot.  Needs to be added to
@@ -10,14 +14,22 @@
 #define ADC_INT 14

 #define ADC_ADDR 0x37
+#define NUM_CHANNELS 4
+
+const String channels[NUM_CHANNELS] = {
+  "hot_water_out",
+  "recirc_return",
+  "cold_water_in",
+  "recirc_pump_in",
+};

 // TODO(z2amiller):  Cut this out into a separate library.
 class TI128D818 {
  public:
   TI128D818();
-  TI128D818(const uint8_t add_addr);
-  bool init(const uint8_t adc_mode = 0);
-  float temp(const uint8_t channel = 0);
+  TI128D818(const uint8_t adc_addr);
+  bool Init(const uint8_t adc_mode = 0);
+  uint16_t RawValue(const uint8_t channel);
  private:
   uint8_t read8(const uint8_t addr);
   uint16_t read16(const uint8_t addr);
@@ -35,7 +47,6 @@
 }

 // TODO(z2amiller):  Have a maximum allowed elapsed time?
-// TODO(z2amiller):  Can't dump to serial in a library.  #ifdef debug?
 void TI128D818::pollUntilReady() {
   int delay_time = 33;
   while (true) {
@@ -49,32 +60,23 @@
   }
 }

-
-// TODO(z2amiller):  Have the TI128D818 library only return the raw
-//                   temperature value, this temperature conversion
-//                   is very application specific.
-float TI128D818::temp(const uint8_t channel) {
-  uint16_t t = read16(channel);
+// Takes the channel number (0 - 8).  If given an invalid
+// channel, returns 0.  The actual I2C channel ID is offset
+// by 0x20.
+uint16_t TI128D818::RawValue(const uint8_t channel) {
+  if (channel < 0 || channel > 8) {
+    return 0;
+  }
   // This is a 12 bit ADC; bit shift this 16 bit value to get the
   // 12 bits we are interested in.
-  t >>= 4;
-  // Calculate the actual temperature using the Steinhart-Hart
-  // formula.
-  const int measured_resistance = 10000.0 * ((4096.0 / t) - 1);
-  const float mr_log = log(measured_resistance / 10000.0);
-  // Steinhart-hart coefficients for the Vishay NTCLG100E2103.
-  // (10K @ 25C thermistor)
-  const float tempK = 1 / (0.003354016 +
-                          (0.0002569850 * mr_log) +
-                          (0.000002620131 * pow(mr_log, 2)) +
-                          (0.00000006383091 * pow(mr_log, 3)));
-  return tempK - 273.15; // tempC
+  return read16(channel + 0x20) >> 4;
 }
+

 // TODO(z2amiller):  Provide a configuration class that encapsulates
 //                   all of the ADC configuration options.
 //                   (pins, modes, etc).
-bool TI128D818::init(const uint8_t adc_mode) {
+bool TI128D818::Init(const uint8_t adc_mode) {
   Wire.begin(SDAPIN, SCLPIN);
   write8(0x00, 0x00); // disable all.
   pollUntilReady();
@@ -116,25 +118,41 @@
 }

 TI128D818 adc = TI128D818();
+PrometheusClient prom = PrometheusClient(SERVER_IP, SERVER_PORT,
+                                         "OctoTemp", "WaterHeater");
+
 void setup(void)
 {
   Serial.begin(115200);
-  adc.init(0x1);
+  adc.Init(0x1);
+}
+
+float TempC(const uint8_t channel) {
+  const uint16_t t = adc.RawValue(channel);
+  const int measured_resistance = 10000.0 * ((4096.0 / t) - 1);
+  const float mr_log = log(measured_resistance / 10000.0);
+  // Steinhart-Hart coefficients for the Vishay NTCLG100E2103.
+  // (10K @ 25C thermistor)
+  const float tempK = 1 / (0.003354016 +
+                          (0.0002569850 * mr_log) +
+                          (0.000002620131 * pow(mr_log, 2)) +
+                          (0.00000006383091 * pow(mr_log, 3)));
+  return tempK - 273.15; // tempC
+}
+
+float TempF(const uint8_t channel) {
+  return TempC(channel) * 1.8 + 32;
 }

 // TODO(z2amiller):  Do something interesting with this data.
 //                   Post to prometheus or MQTT or something.
 void loop(void)
 {
-  Serial.print("ch 0 = ");
-  Serial.print(adc.temp(0x20));
-  Serial.print("  ch 1 = ");
-  Serial.print(adc.temp(0x21));
-  Serial.println("");
-  Serial.print("ch 2 = ");
-  Serial.print(adc.temp(0x22));
-  Serial.print("  ch 3 = ");
-  Serial.print(adc.temp(0x23));
-  Serial.println("");
+  for (int ch = 0; ch < NUM_CHANNELS; ch++) {
+    prom.AddGauge("octo_sensor_tempF", TempF(ch),
+                  "location=\"" + channels[ch] + "\"");
+    Serial.println(channels[ch] + "(" + ch + ") = " + TempF(ch));
+  }
+  prom.Send();
   delay(5000);
 }


Motors were switched, corrected

Motors were switched, corrected

--- Running_Motors/Running_Motors.ino
+++ Running_Motors/Running_Motors.ino
@@ -4,8 +4,8 @@
 // concise.

 // create the variables that defines which pins the motors are connected to
-const int leftMotorPins[3] = {4, 5, 6};
-const int rightMotorPins[3] = {7, 8, 9};
+const int rightMotorPins[3] = {4, 5, 6};
+const int leftMotorPins[3] = {7, 8, 9};

 //----------//
 // This is the set-up for all of the pins you are using on the Arduino
@@ -32,7 +32,7 @@
 //This is the main section of your code, it repeatedly loops through.
 void loop() {

-  // this tells the motors to run (default value is 100), change this and see what happens.
+  // this tells the motors to run at 100 change this and see what happens.
   analogWrite(leftMotorPins[2], 100);
   analogWrite(rightMotorPins[2], 100);
   delay(20); // this delay is necessary to give it a little more time to move and process.


RobotFirmware:removed delay in main loop

--- platform_src/RobotFirmware/RobotFirmware.ino
+++ platform_src/RobotFirmware/RobotFirmware.ino
@@ -56,7 +56,6 @@
   IR_update();
   Floor_update();
   Compass_update();
-  delay(50);
 }

 void IR_update(){


Fixed bug where module would not activate WiFi serial port


Fix UTC offset not working

Fix UTC offset not working

--- wled00/wled10_ntp.ino
+++ wled00/wled10_ntp.ino
@@ -164,9 +164,9 @@
 bool checkCountdown()
 {
   unsigned long n = now();
-  local = countdownTime - n;
+  if (countdownMode) local = countdownTime - n + utcOffsetSecs;
   if (n > countdownTime) {
-    local = n - countdownTime;
+    if (countdownMode) local = n - countdownTime + utcOffsetSecs;
     if (!countdownOverTriggered)
     {
       if (macroCountdown != 0) applyMacro(macroCountdown);


used different way to compare heat index

--- QmoteRHTlogger_w_Daikin/QmoteRHTlogger_w_Daikin.ino
+++ QmoteRHTlogger_w_Daikin/QmoteRHTlogger_w_Daikin.ino
@@ -32,15 +32,14 @@

 //  ambient environmental parameters
 #define TEMP_SETTING          24          // cooling setting to this temperature
-#define TEMP_HIGH             27.8        // restart cooling if temperature reaches this measurement
+#define HEAT_INDEX_HIGH       27.8        // restart cooling if temperature reaches this measurement
+#define HEAT_INDEX_TOO_HIGH   29          // use Heat Index to check if the ambient condition needs to be changed, if so, KEEP_OFF_TIMER will be ignored
 #define TEMP_LOW              25          // stop cooling or switch to humidifier if temerature reaches this measurement
 #define TEMP_TOO_LOW          23          // if temperature reaches this value means humidifier goes too much, turn off everything
-#define HEAT_INDEX_TOO_HIGH   29.5        // use Heat Index to check if the ambient condition needs to be changed, if so, KEEP_OFF_TIMER will be ignored
 #define RH_HIGH               68          // restart humidifier if Rh reaches to this measurement
 #define RH_LOW                60          // stop humidifier if Rh reaches to this measurement

-// once the air conditioning is OFF due to the ambient condition reaches the criteria,
-// do not turn it ON for certain amount of time
+// avoid frequent ON-OFF mode switch
 #define KEEP_ONOFF_TIMER      90

 // when Qmote is disconnected, a timer counts the time before it is reconnected back
@@ -272,12 +271,8 @@
 unsigned int teim = timeElapsed / (long) 60000;
 qmoteCmd = "ATBN=0x0A,\"";      // using click combination code 0x0A
 qmoteCmd += isOn;
+qmoteCmd += ",";
 qmoteCmd += teim;
-qmoteCmd += currentRhInt;
-qmoteCmd += ",";
-qmoteCmd += currentTemp;
-qmoteCmd += ",";
-qmoteCmd += currentHeatIndex;
 qmoteCmd += "\"\r\n";
 portOne.write(qmoteCmd.c_str());
 delay(3000);
@@ -385,15 +380,18 @@
       // Calculate Heat Index
       float curHeatIndex = heatIndex((double) currentTemp, (double) currentRh);

-      // check if the ambient condition exceed the limit
-      if((((float) curHeatIndex) >= ((float) HEAT_INDEX_TOO_HIGH)) ||
-         (((float) currentTemp) <= ((float) TEMP_TOO_LOW)))
+      // the following conditions will ignore the ON-OFF timer
+      if(
+         (((float) curHeatIndex) >= ((float) HEAT_INDEX_TOO_HIGH)) ||                                       // heat index too high
+         (((float) currentTemp) <= ((float) TEMP_TOO_LOW)) ||                                               // temperature too low
+         (isOn == MODE_COOLING && ((float) currentTemp) < ((float) TEMP_LOW) && currentRh > RH_LOW) ||      // cooling -> dehumidifier
+         (isOn == MODE_DEHUMIDIFIER &&                                                                      // dehumidifier -> cooling
+          ((((float) currentTemp) > ((float) TEMP_LOW) && currentRh < RH_LOW) ||
+           ((float) curHeatIndex >= (float) HEAT_INDEX_HIGH)))
+        )
       {
         // ambient condition exceeds the limit, skip the KEEP_ONOFF_TIMER
         timeElapsed = (long) KEEP_ONOFF_TIMER * (long) 60000;
-
-        // repeat the last command if the mode is not changed in the later check
-        resend = 0;
       }

       // once the air conditioning mode is switched, keep the state for a certain amount of time
@@ -405,8 +403,8 @@
         if(isOn == MODE_OFF)
         {
           // assume current air conditioning is OFF
-          // temperature priority
-          if((float) currentTemp >= (float) TEMP_HIGH)
+          // heat index (temperature) priority
+          if((float) curHeatIndex >= (float) HEAT_INDEX_HIGH)
           {
             resend = 0;
             resend_attempts = 1;
@@ -446,7 +444,7 @@
             daikin_all_off();
           }
           else if((((float) currentTemp) > ((float) TEMP_LOW) && currentRh < RH_LOW) ||   // humidity reaches low but temperature is higher than low
-                  ((float) currentTemp >= (float) TEMP_HIGH))                             // temperature reaches high no matter how much humidity is
+                  ((float) curHeatIndex >= (float) HEAT_INDEX_HIGH))                      // heat index reaches high no matter how much humidity is
           {
             resend = 0;
             resend_attempts = 1;


Fix some minor typos preventing compile

Fix some minor typos preventing compile

--- crypt-gears/gear_arduino/gear_arduino.ino
+++ crypt-gears/gear_arduino/gear_arduino.ino
@@ -77,15 +77,6 @@
 {
   Serial.begin(9600);

-  // init all gear connections as inputs
-  for(int i=0; i<3; i++)
-  {
-    for(int j=0; j<12; j++)
-    {
-      pinMode(gear_connections[i][j], INPUT);
-    }
-  }
-
   // init all output lights as outputs which are off
   for(int i=0; i<7; i++)
   {
@@ -159,13 +150,13 @@
         int types_seen = 0;
         for (int i=0; i<3; i++)
         {
-          if (!computeGearPositions(i))
+          if (!computeGearPosition(i))
           {
             failed = true;
           }
           else
           {
-            types_seen |= 1 << gear_types[i]
+            types_seen |= 1 << gear_types[i];
           }
         }

@@ -253,7 +244,7 @@
   int positions_white = 0;
   for (int j=0; j<7; j++)
   {
-    positions_white += photoresistor_history[i][j]
+    positions_white += photoresistor_history[i][j];
   }

   // If we saw 2 white, they should be in 1, 4 or 2, 5, and that means we have


IR beacon test

IR beacon test

--- Tests/IRBeacon_analog_test/IRBeacon_analog_test.ino
+++ Tests/IRBeacon_analog_test/IRBeacon_analog_test.ino
@@ -1,22 +1,29 @@
-int irBeaconPin = A0;
-float irBeaconValue, tmpSum, irBeaconMeanValue;
+int irBeaconPinLeft  = A0;
+int irBeaconPinRight = A1;
+float irBeaconLeftVal, irBeaconRightVal, tmpSum, irBeaconMeanValue;
 int nbrAvRuns = 1;

 void setup() {
-  // put your setup code here, to run once:
   Serial.begin(9600);
-  pinMode(irBeaconPin,INPUT);
+  pinMode(irBeaconPinLeft, INPUT);
+  pinMode(irBeaconPinRight,INPUT);
 }

 void loop() {
-  // put your main code here, to run repeatedly:
-  irBeaconMeanValue = 0; tmpSum = 0;
+  int tmpSumLeft = 0;
+  int tmpSumRight = 0;
   for (int k = 1; k<=nbrAvRuns; k++){
-    irBeaconValue = digitalRead(irBeaconPin);
+    irBeaconLeftVal = analogRead(irBeaconPinLeft)*5.0/1024.0;
+    irBeaconRightVal = analogRead(irBeaconPinRight)*5.0/1024.0;
     //irBeaconValue = irBeaconValue*5/1024;
-    tmpSum += irBeaconValue;
+    tmpSumLeft  += irBeaconLeftVal;
+    tmpSumRight += irBeaconRightVal;
   };
-  irBeaconMeanValue = tmpSum/nbrAvRuns;
-  Serial.println(irBeaconMeanValue);
+  int irBeaconMeanLeft  = tmpSumLeft/nbrAvRuns;
+  int irBeaconMeanRight = tmpSumRight/nbrAvRuns;
+  Serial.println(
+    "Left: "  + String(irBeaconMeanLeft) + "\t" +
+    "Right: " + String(irBeaconMeanRight)
+  );
   delay(100);
 }


Added output to show speed

Added output to show speed

--- gps_arduino/gps_arduino.ino
+++ gps_arduino/gps_arduino.ino
@@ -5,7 +5,7 @@
 //gps 3,4
 //mag A4 A5
 //Heading Adjust A2
-//Speed Adjust A1
+//Speed Adjust A2

 #include <LiquidCrystal.h>
 #include <SoftwareSerial.h>
@@ -36,8 +36,8 @@
 //END Easy Transfer

 //Motor speed -127 to 127
-#define SPEED 80
-#define TURN_SPEED 55
+#define SPEED 127
+#define TURN_SPEED 100

 #define I2C_ADDR 0x27  // Define I2C Address where the PCF8574A is
@@ -72,7 +72,7 @@
 #define HEADING_ADJUST_PIN A2

 //Speed control
-#define SPEED_ADJUST_PIN A1
+#define SPEED_ADJUST_PIN A3
 int mSpeedCap = 0;

 // 2x16 LCD stuff
@@ -378,7 +378,9 @@
          lcd2.print(F(")"));
          lcd2.setCursor(0,3);
          lcd2.print(F("SAT: "));
-         lcd2.print(gps.satellites() == TinyGPS::GPS_INVALID_SATELLITES ? DEC: gps.satellites());
+         lcd2.print(gps.satellites() == TinyGPS::GPS_INVALID_SATELLITES ? 0 : gps.satellites());
+         lcd2.print(F(" SPEED: -"));
+         lcd2.print(mSpeedCap);
          //delay 1000);

        break;


Added delay after Serial init to help detect baud rate on first try.

--- software/CopernicusTerm/CopernicusTerm.ino
+++ software/CopernicusTerm/CopernicusTerm.ino
@@ -43,6 +43,7 @@

   Serial.begin( 115200 );
   while( !Serial );
+  delay( 1000 );
   findBaudRate();

   // clear input buffer