Temp checking for working HMTL_Module fade program

--- HMTL_Module/HMTL_Module.ino
+++ HMTL_Module/HMTL_Module.ino
@@ -4,7 +4,9 @@
  * Copyright: 2014
  *
  * Code for a fully contained module which handles HMTL formatted messages
- * from a serial or RS485 connection.
+ * from a serial, RS485, or XBee connection.   It also functions as a bridge
+ * router, retransmitting messages from one connections over any others that
+ * are present.
  ******************************************************************************/

 #include "EEPROM.h"
@@ -13,8 +15,13 @@
 #include "SPI.h"
 #include "FastLED.h"
 #include "Wire.h"
-
-#define DEBUG_LEVEL DEBUG_HIGH
+#include "XBee.h"
+
+
+
+#ifndef DEBUG_LEVEL
+  #define DEBUG_LEVEL DEBUG_HIGH
+#endif
 #include "Debug.h"

 #include "GeneralUtils.h"
@@ -28,12 +35,13 @@

 #include "Socket.h"
 #include "RS485Utils.h"
+#include "XBeeSocket.h"
 #include "MPR121.h"

 #include "HMTL_Module.h"

 /* Auto update build number */
-#define HMTL_MODULE_BUILD 18 // %META INCR
+#define HMTL_MODULE_BUILD 22 // %META INCR

 #define TYPE_HMTL_MODULE 0x1

@@ -73,9 +81,17 @@
 program_tracker_t *active_programs[HMTL_MAX_OUTPUTS];

+#define SEND_BUFFER_SIZE 64 // The data size for transmission buffers
+
+boolean has_rs485;
 RS485Socket rs485;
-config_rgb_t rgb_output;
-config_value_t value_output;
+byte rs485_data_buffer[RS485_BUFFER_TOTAL(SEND_BUFFER_SIZE)];
+byte *rs485_send_buffer;
+
+boolean has_xbee;
+XBeeSocket xbee;
+byte xbee_data_buffer[RS485_BUFFER_TOTAL(SEND_BUFFER_SIZE)];
+byte *xbee_send_buffer;

 config_hdr_t config;
 output_hdr_t *outputs[HMTL_MAX_OUTPUTS];
@@ -84,9 +100,7 @@

 PixelUtil pixels;

-#define SEND_BUFFER_SIZE 64
-byte databuffer[RS485_BUFFER_TOTAL(SEND_BUFFER_SIZE)];
-byte *send_buffer;
+

 /*
  * Data from sensors, set to highest analog value
@@ -108,19 +122,38 @@
   }

   int32_t outputs_found = hmtl_setup(&config, readoutputs,
-				     outputs, objects, HMTL_MAX_OUTPUTS,
-				     &rs485, &pixels, NULL,
-				     &rgb_output, &value_output,
-				     NULL);
+                                     outputs, objects, HMTL_MAX_OUTPUTS,
+                                     &rs485,
+                                     &xbee,
+                                     &pixels,
+                                     NULL, // MPR121
+                                     NULL, // RGB
+                                     NULL, // Value
+                                     NULL);

   if (!(outputs_found & (1 << HMTL_OUTPUT_RS485))) {
     DEBUG_ERR("No RS485 config found");
     DEBUG_ERR_STATE(1);
   }

-  /* Setup the RS485 connection */
-  rs485.setup();
-  send_buffer = rs485.initBuffer(databuffer);
+  if (outputs_found & (1 << HMTL_OUTPUT_RS485)) {
+    /* Setup the RS485 connection */
+    rs485.setup();
+    rs485_send_buffer = rs485.initBuffer(rs485_data_buffer);
+    has_rs485 = true;
+  } else {
+    has_rs485 = false;
+  }
+
+  if (outputs_found & (1 << HMTL_OUTPUT_XBEE)) {
+    /* Setup the RS485 connection */
+    xbee.setup();
+    xbee_send_buffer = xbee.initBuffer(xbee_data_buffer);
+    has_xbee = true;
+  } else {
+    has_xbee = false;
+  }
+

   DEBUG2_VALUELN("HMTL Module initialized, v", HMTL_MODULE_BUILD);
   Serial.println(F(HMTL_READY));
@@ -164,7 +197,10 @@
    * to some other address, and then apply them locally
    */
   for (byte i = 0; i < STARTUP_MSGS; i++) {
-    boolean forwarded = check_and_forward(startupmsg[i]);
+    boolean forwarded = false;
+    if (has_rs485) {
+      forwarded = check_and_forward(startupmsg[i], &rs485);
+    }
     process_msg(startupmsg[i], false, forwarded);
   }

@@ -220,8 +256,10 @@
     DEBUG_PRINT_END();
     Serial.println(F(HMTL_ACK));

-    /* Forward the message over RS485 if needed */
-    forwarded = check_and_forward(msg_hdr);
+    if (has_rs485) {
+      /* Forward the message over RS485 if needed */
+      forwarded = check_and_forward(msg_hdr, &rs485);
+    }

     if (process_msg(msg_hdr, false, forwarded)) {
       update = true;
@@ -315,7 +353,7 @@
         DEBUG3_VALUELN("Poll req src:", source_address);

         // Format the poll response
-        uint16_t len = hmtl_poll_fmt(send_buffer, SEND_BUFFER_SIZE,
+        uint16_t len = hmtl_poll_fmt(rs485_send_buffer, SEND_BUFFER_SIZE,
                                      source_address,
                                      msg_hdr->flags, TYPE_HMTL_MODULE,
                                      &config, outputs, recv_buffer_size);
@@ -330,9 +368,9 @@
               delay(delayMs);
           }

-          rs485.sendMsgTo(source_address, send_buffer, len);
+          rs485.sendMsgTo(source_address, rs485_send_buffer, len);
         } else {
-          Serial.write(send_buffer, len);
+          Serial.write(rs485_send_buffer, len);
         }

         break;
@@ -380,11 +418,11 @@

 /*
  * Check if a message should be forwarded and transmit it over the
- * rs485 socket if so.
- */
-boolean check_and_forward(msg_hdr_t *msg_hdr) {
+ * a socket if so.
+ */
+boolean check_and_forward(msg_hdr_t *msg_hdr, Socket *socket) {
   if ((msg_hdr->address != config.address) ||
-      (msg_hdr->address == RS485_ADDR_ANY)) {
+      (msg_hdr->address == SOCKET_ADDR_ANY)) {
     /*
      * Messages that are not to this module's address or are on the broadcast
      * address should be forwarded.
@@ -394,13 +432,13 @@
       DEBUG1_VALUELN("Message larger than send buffer:", msg_hdr->length);
     } else {
       DEBUG4_VALUELN("Forwarding serial msg to ", msg_hdr->address);
-      memcpy(send_buffer, msg_hdr, msg_hdr->length);
-      rs485.sendMsgTo(msg_hdr->address, send_buffer, msg_hdr->length);
+      memcpy(socket->send_buffer, msg_hdr, msg_hdr->length);
+      rs485.sendMsgTo(msg_hdr->address, socket->send_buffer, msg_hdr->length);
       return true;
     }
   }

-  // The message was not forwarded over RS485
+  // The message was not forwarded over the socket
   return false;
 }

@@ -737,10 +775,19 @@

 boolean program_fade_init(msg_program_t *msg,
                           program_tracker_t *tracker) {
-  DEBUG3_PRINT("Initializing fade program");
+  DEBUG3_PRINT("Initializing fade program:");

   state_fade_t *state = (state_fade_t *)malloc(sizeof (state_fade_t));
   memcpy(&state->msg, msg->values, sizeof (state->msg));
+  tracker->state = state;
+
+  DEBUG3_VALUE(" ", state->msg.period);
+  DEBUG3_VALUE(" ", state->msg.start_value[0]);
+  DEBUG3_VALUE(",", state->msg.start_value[1]);
+  DEBUG3_VALUE(",", state->msg.start_value[2]);
+  DEBUG3_VALUE(" ", state->msg.stop_value[0]);
+  DEBUG3_VALUE(",", state->msg.stop_value[1]);
+  DEBUG3_VALUELN(",", state->msg.stop_value[2]);

   state->start_time = 0;

@@ -757,6 +804,8 @@
     // Set the initial color
     hmtl_set_output_rgb(output, object, state->msg.start_value);
     changed = true;
+    state->start_time = now;
+    DEBUG5_VALUELN("Fade ms:", now);
   } else {
     // Calculate the color at this time
     CRGB start = CRGB(state->msg.start_value[0],
@@ -773,10 +822,15 @@
       tracker->done = true;
       elapsed = state->msg.period;
     }
-    fract8 fraction = map(elapsed, 0, 255, 0, state->msg.period);
+    fract8 fraction = map(elapsed, 0, state->msg.period, 0, 255);

     CRGB current = blend(start, stop, fraction);
     hmtl_set_output_rgb(output, object, current.raw);
+    changed = true;
+
+    DEBUG5_VALUE("Fade ms:", now);
+    DEBUG5_VALUE(" elapsed:", elapsed);
+    DEBUG5_VALUELN(" fract:", fraction);
   }

   return changed;


Updated software to include an LED strip

--- software/my_shiny_metal_tooth/my_shiny_metal_tooth.ino
+++ software/my_shiny_metal_tooth/my_shiny_metal_tooth.ino
@@ -17,6 +17,8 @@
  *   the code with the same line commented out. If you don't do that, the next time
  *   your Arduino resets, it will write the time again on the RTC...
  *   the time of the code's compilation.
+ * Update:
+ *   An LED strip has been added that shines light down the sign from above.
  *
  * Author:
  *   Nick Lamprianidis { paign10.ln [at] gmail [dot] com }
@@ -36,6 +38,7 @@

 #define DEBUG

+#define LED_STRIP  4
 #define GREEN_WIRE 5
 #define BLUE_WIRE  6

@@ -70,8 +73,10 @@
     #ifdef DEBUG
     Serial.begin (9600);
     while (!Serial) ;
+    Serial.println ("My-Shiny-Metal-Tooth\n");
     #endif

+    pinMode (LED_STRIP, OUTPUT);
     pinMode (GREEN_WIRE, OUTPUT);
     pinMode (BLUE_WIRE, OUTPUT);

@@ -123,6 +128,7 @@
             if (mNow > mSunset && mNow < TURN_OFF_TIME)
                 state = S_ON;

+            digitalWrite (LED_STRIP, LOW);
             digitalWrite (GREEN_WIRE, LOW);
             digitalWrite (BLUE_WIRE, LOW);
             break;
@@ -132,6 +138,8 @@
                 state = S_OFF;
                 break;
             }
+
+            digitalWrite (LED_STRIP, HIGH);

             rNum = rand () % 12;
             if (rNum < 6)      state = L_ON;     // 50%


Changed PWM-Port for the taillight

Changed PWM-Port for the taillight

--- src/Deutsch/NOKO_Schwanzlicht/NOKO_Schwanzlicht.ino
+++ src/Deutsch/NOKO_Schwanzlicht/NOKO_Schwanzlicht.ino
@@ -38,7 +38,7 @@
  * Radio RST        D5
  * Taillight VCC    5V
  * Taillight GND    GND
- * Taillight MOSFET D8    (PWM)
+ * Taillight MOSFET D9    (PWM)
  * JQ6500 GND   13  GND
  * JQ6500 TX    26  D2    (Software-TX), connect with 1kOhm resistor
  * JQ6500 RX    25  D3    (Software-RX)
@@ -113,7 +113,7 @@

 // Hardwareadresses PINS
 #define LED 10            // LED -> PWM
-#define Tail 8            // Taillight -> PWM
+#define Tail 9            // Taillight -> PWM
 #define inPin 12          // Ultrasonic
 #define Akku 6            // Battery power
 #define USB 7             // Is NOKO connected to USB?
@@ -967,7 +967,7 @@
   {
     if (klang==3)
     {
-      if (lightlevel<255) lightlevel+=1;
+      if (lightlevel<255) lightlevel+=4;
       analogWrite(Tail,lightlevel);
     }
     zeichen(5,2,0);


Update main.ino

Update main.ino

--- main/main.ino
+++ main/main.ino
@@ -8,25 +8,45 @@
 */

 #define ENABLE_DEBUG  0  // Set to 1 to enable serial debug out
+#define USE_SCREEN    0 // Set to 1 to use screen, set to 0 not use
+#define BENCH_TIME    0 // Set to 1 to have loop time exec in serial monitor
+
+#if BENCH_TIME || ENABLE_DEBUG
+int looptime = 0 ;
+int looptick = 0;
+#endif
+
 #include "screen.h"
 #include "minimidi.h"
 #include "IOS.h"

 void setup() {
-#if ENABLE_DEBUG
+#if BENCH_TIME || ENABLE_DEBUG
   Serial.begin(115200);
   Serial.println("start setup");
 #endif
+#if USE_SCREEN
   screeninit(); // set screen
+#endif
   outputsinit(); // set outputs
   inputsinit(); // set inputs
 #if ENABLE_DEBUG
   Serial.println("setup end");
 #endif
+#if USE_SCREEN
   clearscreen();
+#endif
 }

 void loop() {
+#if BENCH_TIME || ENABLE_DEBUG
+  looptime = millis() - looptick;
+  if (looptime >= 2) {
+    Serial.print("L00P T!W3: ");
+    Serial.println(looptime);
+  }
+  looptick = millis();
+#endif
   getMidiIn();
   readJogWheel();
   setMidiOut();


indent

indent

--- scripts-arduino/bp_led_lp.ino
+++ scripts-arduino/bp_led_lp.ino
@@ -1,32 +1,30 @@
-// ######## Constantes ########
-const int BUTTON_PIN = 3;        // the number of the pushbutton pin
-const int LED_PIN =  2;          // the number of the LED pin
-const String CONST_ID = "01";   // the main Id
-const String CONST_TYPE = "01"; // the id of press button
+// ######## CONST ########
+const int BUTTON_PIN = 3;           // the number of the pushbutton pin
+const int LED_PIN =  2;             // the number of the LED pin
+const String CONST_ID = "01";       // the main Id
+const String CONST_TYPE = "01";     // the id of press button

+// ######## VAR ########
+int buttonState = 0;                // variable for reading the pushbutton status
+int ledState = 0;                   // variable for the led state
+int currenteState = 0;              // temp variable
+int button_pressed_counter;         // press running duration
+boolean button_was_pressed;         // previous state

-// variables will change:
-int buttonState = 0;            // variable for reading the pushbutton status
-int ledState = 0;
-int currenteState = 0;
-
+// ######## ENUM ########
 enum {
-  EV_NONE=0,
-  EV_SHORTPRESS=1,
-  EV_LONGPRESS=2
+    EV_NONE=0,
+    EV_SHORTPRESS=1,
+    EV_LONGPRESS=2
 };

-boolean button_was_pressed;     // previous state
-int button_pressed_counter;     // press running duration
-
 // ######## SETUP ########
-
 void setup() {
-  Serial.begin(9600);
-  pinMode(ledPin, OUTPUT);          // initialize the LED pin as an output:
-  pinMode(buttonPin, INPUT);        // initialize the pushbutton pin as an input:
-  button_was_pressed = false;       // initialize the pushbutton to false (not pressed)
-  button_pressed_counter = 0;       // initialize the pusbutton counter
+    Serial.begin(9600);
+    pinMode(ledPin, OUTPUT);          // initialize the LED pin as an output:
+    pinMode(buttonPin, INPUT);        // initialize the pushbutton pin as an input:
+    button_was_pressed = false;       // initialize the pushbutton to false (not pressed)
+    button_pressed_counter = 0;       // initialize the pusbutton counter
 }

 // ######## LOOP ########
@@ -57,7 +55,6 @@
 }

 // ####### Function ########
-
 int handle_button(){
     int event;
     int button_now_pressed = !digitalRead(BUTTON_PIN); // pin low -> pressed
@@ -85,7 +82,6 @@

 // ######## METHODES ########
-
 // turn LED on:
 void turnOn(){
     digitalWrite(LED_PIN, HIGH);


inserimento dei commenti

inserimento dei commenti

--- nodeMCU/plant/functions.ino
+++ nodeMCU/plant/functions.ino
@@ -16,18 +16,25 @@
 void sendRnd(int rnd)
 {
    WiFiClient client;
-
+
+   //cerca di stabilire una connessione al server sulla porta 3000,
+   //nel caso ci dovesse riuscire invia al monitor seriale un feedback
    if (client.connect(server, 3000)) {
    Serial.println("WiFi Client connected ");

+   //converte in oggetto Stringa il parametro ricevuto
    String postStr= String(rnd);

+   //costruisce la stringa da inviare, si noti il parametro GET che denota il metodo scelto
    String url = "GET /dato/acquisisci/" + postStr + " HTTP/1.1";
    Serial.println(postStr);

+   //tutte le istruzioni sono duplicate per poter inviare la stessa sequenza di dati
+   //al server Node e al monitor seriale
    client.println(url);
    Serial.println(url);

+   //per poter inviare correttamente una richiesta di tipo GET bisogna indicare l'HOST di destniazione
    client.println("Host: 192.168.1.67:3000");
    Serial.println("Host: 192.168.1.67:3000");

@@ -35,7 +42,8 @@
    Serial.println("Connection: close");

    client.println();
-
+
+   //generiamo il beep di notifica dell'invio del dato.
    Serial.println();
    digitalWrite(14, HIGH);
    delay(500);


final functional code without final print statements

--- simulation_environment/simulation_environment.ino
+++ simulation_environment/simulation_environment.ino
@@ -2,8 +2,8 @@
 #include "RestClient.h"   // Library Downloaded from: https://github.com/DaKaZ/esp8266-restclient
 #include "cardIDS.h"

-#define WiFi_ID       ""
-#define WiFi_Password ""
+#define WiFi_ID       "HEXA"
+#define WiFi_Password "hexapassword"

 #define SWITCH_PIN    5
 #define Green_Led     15
@@ -11,7 +11,7 @@

 RestClient client = RestClient("unlv-spots.herokuapp.com");
 String lotID, cardID;
-int lotNUM;
+int lotNUM, dbSuccess, dbFailure;
 long randIndex;
 //bool vacant;

@@ -49,7 +49,7 @@
       lotID = "0" + String(lotNUM);
     else
       lotID = "00" + String(lotNUM);
-    lotID = "0100";
+    //lotID = "0100";

     if(getVacancy()) {
       updateVacancy("/false");
@@ -72,6 +72,7 @@
       flash_LED(Green_Led, 2000);
     }
     Serial.println();
+    delay(2000);

   }

@@ -123,7 +124,16 @@
   const char* c = dbPath.c_str();
   Serial.println(dbPath);
   int statusCode = client.post(c, "POSTDATA", &response);
-
+  if(statusCode == 200)
+    dbSuccess++;
+  else
+    dbFailure++;
+  Serial.print("Successful DB Requests: ");
+  Serial.println(dbSuccess);
+  Serial.print("Failed DB Requests: ");
+  Serial.println(dbFailure);
+  Serial.println(statusCode);
+
 }

 bool swipeCard() {
@@ -133,12 +143,23 @@
   dbPath += lotID;
   randIndex = random(1, 100);
   cardID = randomCard(int(randIndex));
+  dbPath += "/";
+  dbPath += cardID;

   const char* c = dbPath.c_str();
   Serial.print("Checking for authorization of cardID: ");
   Serial.println(cardID);
   Serial.println(dbPath);
   int statusCode = client.post(c, "POSTDATA", &response);
+  if(statusCode == 200)
+    dbSuccess++;
+  else
+    dbFailure++;
+  Serial.print("Successful DB Requests: ");
+  Serial.println(dbSuccess);
+  Serial.print("Failed DB Requests: ");
+  Serial.println(dbFailure);
+  Serial.println(statusCode);

   if(response == "{\"authorized\":true}")
     return true;
@@ -156,8 +177,15 @@
   const char* c = dbPath.c_str();
   Serial.println(dbPath);
   int statusCode = client.get(c, &response);
+  if(statusCode == 200)
+    dbSuccess++;
+  else
+    dbFailure++;
+  Serial.print("Successful DB Requests: ");
+  Serial.println(dbSuccess);
+  Serial.print("Failed DB Requests: ");
+  Serial.println(dbFailure);
   Serial.println(statusCode);
-  Serial.println(response);

   if(response == "{\"Vacancy\":true}")
     return true;


Implement current limiting. When we hit close limit, coast ahead at slow speed until the current limit is reached.

--- KomaRoof.ino
+++ KomaRoof.ino
@@ -39,8 +39,10 @@
 #define PIN_BUTTON_EMERGENCYSTOP 3
 #define PIN_LIMITSWITCH_OPEN 18
 #define PIN_LIMITSWITCH_CLOSE 19
+#define MOTOR_CURRENT_LIMIT_MILLIAMPS 2500
 #define MOTOR_POLARITY 1    // Change to -1 to invert movement direction
 #define FULL_SPEED 400
+#define CLOSING_SPEED 50
 #define RAMP_LENGTH 20      // two seconds

 void motorTick();
@@ -87,6 +89,8 @@
     handler.registerCommand("CLOSE", close);
     handler.registerCommand("STOP", stop);

+    powerConsumptionLog.setOverloadThreshold(MOTOR_CURRENT_LIMIT_MILLIAMPS);
+
     taskScheduler.init();
     taskScheduler.addTask(motorTask);
     taskScheduler.addTask(buttonTask);
@@ -130,6 +134,17 @@
     if (countSincePhase % 10 == 0) {
         status("");
         powerConsumptionLog.report(serial);
+    }
+
+    if (powerConsumptionLog.isOverload()) {
+        motorShield.setM1Speed(0);
+        if (roofState == CLOSING && phase == CLOSE_TIGHTLY) {
+            roofState = CLOSED;
+            phase = IDLE;
+        } else {
+            roofState = ERROR;
+            phase = IDLE;
+        }
     }

     if (emergencyStopPressed) {
@@ -168,20 +183,24 @@
         }
         case RAMP_DOWN: {
             int power = FULL_SPEED - FULL_SPEED * countSincePhase / RAMP_LENGTH;
-            if (power < 0)
-                power = 0;
+            int minimumPower = (roofState == CLOSING ? CLOSING_SPEED : 0);
+            if (power < minimumPower)
+                power = minimumPower;
             motorShield.setM1Speed(power * direction);
-            if (power == 0) {
+            if (power == minimumPower) {
                 phase = IDLE;
                 if (roofState == STOPPING)
                     roofState = STOPPED;
                 else if (roofState == OPENING)
                     roofState = OPEN;
                 else if (roofState == CLOSING)
-                    roofState = CLOSED;
+                    phase = CLOSE_TIGHTLY;
             }
             break;
         }
+        case CLOSE_TIGHTLY:
+            // just coast ahead, until we trigger current limit when the roof hits the wall
+            break;
     }
 }

@@ -242,7 +261,7 @@
 }

 void status(const String&) {
-    static const char* roofStateNames[] = { "STOPPED", "OPEN", "CLOSED", "OPENING", "CLOSING", "ERROR" };
+    static const char* roofStateNames[] = { "STOPPED", "OPEN", "CLOSED", "OPENING", "CLOSING", "STOPPING", "ERROR" };
     static const char* phaseNames[] = { "IDLE", "RAMP_UP", "MOVE_UNTIL_NEAR", "RAMP_DOWN", "CLOSE_TIGHTLY" };

     String message = "STATUS,";


Use timer abort only during opening and closing

--- KomaRoof.ino
+++ KomaRoof.ino
@@ -194,7 +194,7 @@

 void timerTick() {
     unsigned long t = millis();
-    if (t - moveStartTime > MAX_MOVE_DURATION) {
+    if ((roofState == OPENING || roofState == CLOSING) && (t - moveStartTime > MAX_MOVE_DURATION)) {
         motorShield.setM1Speed(0);
         motorShield.setM2Speed(0);
         roofState = ERROR;


COH-80: WIP

COH-80: WIP

--- Arduino/COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
+++ Arduino/COHEAT2015/20160316-COHEAT-M1/COHEAT-M1/COHEAT-M1.ino
@@ -343,7 +343,7 @@
     {
     uint8_t txbuf[OTProtocolCC::CC1Alert::primary_frame_bytes+1]; // More than large enough for preamble + sync + alert message.
     const uint8_t bodylen = a.encodeSimple(txbuf, sizeof(txbuf), true);
-    // Send loud since the hub may be relatively far away,
+    // Send loud (high power and/or double) since the hub may be relatively far away,
     // there is no 'ACK', and these messages should not be sent very often.
     // Should be consistent with automatically-generated alerts to help with diagnosis.
     return(PrimaryRadio.sendRaw(txbuf, bodylen, 0, OTRadioLink::OTRadioLink::TXmax));
@@ -351,10 +351,7 @@
 #else
   uint8_t key[16];
   if(!OTV0P2BASE::getPrimaryBuilding16ByteSecretKey(key))
-    {
-    OTV0P2BASE::serialPrintlnAndFlush("!TX key");
-    return(false); // Failed.
-    }
+    { OTV0P2BASE::serialPrintlnAndFlush("!TX key"); return(false); } // FAIL
   const OTRadioLink::SimpleSecureFrame32or0BodyTXBase::fixed32BTextSize12BNonce16BTagSimpleEnc_ptr_t e = OTAESGCM::fixed32BTextSize12BNonce16BTagSimpleEnc_DEFAULT_STATELESS;
   uint8_t buf[OTRadioLink::SimpleSecureFrame32or0BodyTXBase::generateSecureBeaconMaxBufSize];
   const uint8_t bodylen = secureTXState.generateSecureBeaconRawForTX(buf, sizeof(buf), lenTXID, e, NULL, key); // 2 byte ID.
@@ -579,9 +576,7 @@
   // Get the 'building' key.
   if(!OTV0P2BASE::getPrimaryBuilding16ByteSecretKey(key))
     {
-#if 1 && defined(DEBUG)
-DEBUG_SERIAL_PRINTLN_FLASHSTRING("!RX key");
-#endif
+    DEBUG_SERIAL_PRINTLN_FLASHSTRING("!RX key");
     return; // FAIL
     }
   // Attempt to authenticate (and decrypt) the frame before inspecting content.
@@ -735,15 +730,35 @@
           // TODO: may need to insert a delay to allow hub to be ready if use of read() above is not enough.
           uint8_t txbuf[OTProtocolCC::CC1PollResponse::primary_frame_bytes+1]; // More than large enough for preamble + sync + alert message.
           const uint8_t bodylen = r.encodeSimple(txbuf, sizeof(txbuf), true);
-#if 0 && defined(DEBUG)
-OTRadioLink::printRXMsg(p, txbuf, bodylen);
-#endif
-          if(PrimaryRadio.sendRaw(txbuf, bodylen)) // Send at default volume...  One going missing won't hurt that much.
-            {
 #if 1 && defined(DEBUG)
-            p->println(F("polled")); // Done it!
-#endif
-            }
+          p->println(F("polled"));
+#endif
+#if !defined(ENABLE_OTSECUREFRAME_ENCODING_SUPPORT)
+          // Non-secure: send raw frame as-is.
+          // Send at default power...  One going missing won't hurt that much.
+          if(!PrimaryRadio.sendRaw(txbuf, bodylen))
+            { OTV0P2BASE::serialPrintlnAndFlush("!TX fail"); return; } // FAIL
+#else
+          // Secure: wrap frame in encrypted layer...
+          uint8_t key[16];
+          if(!OTV0P2BASE::getPrimaryBuilding16ByteSecretKey(key))
+            { OTV0P2BASE::serialPrintlnAndFlush("!TX key"); return; } // FAIL
+          const OTRadioLink::SimpleSecureFrame32or0BodyTXBase::fixed32BTextSize12BNonce16BTagSimpleEnc_ptr_t e = OTAESGCM::fixed32BTextSize12BNonce16BTagSimpleEnc_DEFAULT_STATELESS;
+          uint8_t buf[OTRadioLink::SecurableFrameHeader::maxSmallFrameSize];
+
+
+
+
+
+// FIXME FIXME FIXME
+
+
+
+
+
+
+          OTV0P2BASE::serialPrintlnAndFlush("!TX not impl"); // FAIL
+#endif // !defined(ENABLE_OTSECUREFRAME_ENCODING_SUPPORT)
           }
         }
       return;
@@ -1117,12 +1132,34 @@
           {
           uint8_t txbuf[OTProtocolCC::CC1PollAndCommand::primary_frame_bytes+1]; // More than large enough for preamble + sync + alert message.
           const uint8_t bodylen = q.encodeSimple(txbuf, sizeof(txbuf), true);
-          // TX at normal volume since ACKed and can be repeated if necessary.
+#if !defined(ENABLE_OTSECUREFRAME_ENCODING_SUPPORT)
+          // Non-secure: send raw frame as-is.
+          // TX at normal power since ACKed and can be repeated if necessary.
           if(PrimaryRadio.sendRaw(txbuf, bodylen))
-            { return(true); } // Done it!
-#if 1 && defined(DEBUG)
-          else { DEBUG_SERIAL_PRINT_FLASHSTRING("!TX failed"); }
-#endif
+            { return(true); } // Success!
+#else
+          // Secure: wrap frame in encrypted layer...
+          uint8_t key[16];
+          if(!OTV0P2BASE::getPrimaryBuilding16ByteSecretKey(key))
+            { OTV0P2BASE::serialPrintlnAndFlush("!TX key"); return(false); } // FAIL
+          const OTRadioLink::SimpleSecureFrame32or0BodyTXBase::fixed32BTextSize12BNonce16BTagSimpleEnc_ptr_t e = OTAESGCM::fixed32BTextSize12BNonce16BTagSimpleEnc_DEFAULT_STATELESS;
+          uint8_t buf[OTRadioLink::SecurableFrameHeader::maxSmallFrameSize];
+
+
+
+
+
+// FIXME FIXME FIXME
+
+
+
+
+
+
+          OTV0P2BASE::serialPrintlnAndFlush("!TX not impl"); // FAIL
+#endif // !defined(ENABLE_OTSECUREFRAME_ENCODING_SUPPORT)
+          // Fall-through is failure...
+          DEBUG_SERIAL_PRINT_FLASHSTRING("!TX fail");
           }
         }
       }


Add bumper pubs, remove obsolete debug pubs. (#42)

* Add bumper pubs, remove obsolete debug pubs.

--- Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
+++ Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
@@ -35,6 +35,7 @@
 #include <std_msgs/String.h>
 #include <victoria_debug_msgs/TeensyDebug.h>
 #include <victoria_nav_msgs/Odom2DRaw.h>
+#include <victoria_sensor_msgs/ContactState1D.h>
 #include <victoria_sensor_msgs/IMURaw.h>

 // Teensy pin definitions
@@ -112,31 +113,36 @@
 victoria_sensor_msgs::IMURaw ros_raw_imu_msg;
 ros::Publisher ros_raw_imu_pub("imu_raw", &ros_raw_imu_msg);

+// Bumper publishers
+victoria_sensor_msgs::ContactState1D ros_bumper_left_msg;
+victoria_sensor_msgs::ContactState1D ros_bumper_right_msg;
+ros::Publisher ros_bumper_left_pub("bumper_left", &ros_bumper_left_msg);
+ros::Publisher ros_bumper_right_pub("bumper_right", &ros_bumper_right_msg);
+
 // Position of robot
 geometry_msgs::Pose2D pose;

-char ros_odom_header_frame_id[] = "/odom";
-char ros_odom_child_frame_id[] = "/base_link";
-
+// Debug publishers
 char debug_str[80];
 std_msgs::String ros_debug_msg;

-ros::Publisher ros_bumper_debug_pub("bumper_debug", &ros_debug_msg);
-ros::Publisher ros_encoder_debug_pub("encoder_debug", &ros_debug_msg);
 victoria_debug_msgs::TeensyDebug teensy_debug_msg;
 ros::Publisher ros_teensy_debug_pub("teensy_debug", &teensy_debug_msg);

 // Debug blink
-// Blink duration is in milliseconds.
-const int BLINK_DURATION(500);
+// Blink duration is in hertz.
+const int BLINK_FREQ_HZ(2);
 int blink_state = LOW;
-
+
+// Forward declarations
+void setupTimerCallback(int callback_freq_hz, void (*callback)(void));
+
 void setup() {
   // Register ros publishers
   ros_nh.advertise(ros_raw_odom_pub);
   ros_nh.advertise(ros_raw_imu_pub);
-  ros_nh.advertise(ros_bumper_debug_pub);
-  ros_nh.advertise(ros_encoder_debug_pub);
+  ros_nh.advertise(ros_bumper_left_pub);
+  ros_nh.advertise(ros_bumper_right_pub);
   ros_nh.advertise(ros_teensy_debug_pub);

   // Register ros subscribers
@@ -161,12 +167,9 @@
   int publish_raw_imu_freq_hz =
     ros_param_helper.getParam("publish_raw_imu_freq_hz", 2);

-  int publish_bumper_debug_info_freq_hz =
-    ros_param_helper.getParam("publish_bumper_debug_info_freq_hz", 10);
-
-  int publish_encoder_debug_info_freq_hz =
-    ros_param_helper.getParam("publish_encoder_debug_info_freq_hz", 10);
-
+  int publish_bumper_info_freq_hz =
+    ros_param_helper.getParam("publish_bumper_info_freq_hz", 10);
+
   int publish_teensy_debug_info_freq_hz =
     ros_param_helper.getParam("publish_teensy_debug_info_freq_hz", 1);

@@ -218,18 +221,19 @@
   pinMode(BLINK_PIN, OUTPUT);

   // Setup Timer callbacks
-  timer.every(convertFreqToMillis(read_encoders_freq_hz), doReadEncoders);
-  timer.every(convertFreqToMillis(motor_controller_freq_hz), doMotorController);
-  timer.every(convertFreqToMillis(publish_raw_odom_freq_hz), doPublishRawOdom);
-  timer.every(convertFreqToMillis(publish_raw_imu_freq_hz), doPublishRawImu);
-  timer.every(convertFreqToMillis(publish_bumper_debug_info_freq_hz), doBumperDebug);
-  timer.every(convertFreqToMillis(publish_encoder_debug_info_freq_hz), doEncoderDebug);
-  timer.every(convertFreqToMillis(publish_teensy_debug_info_freq_hz), doTeensyDebug);
-  timer.every(BLINK_DURATION, doBlink);
+  setupTimerCallback(read_encoders_freq_hz, doReadEncoders);
+  setupTimerCallback(motor_controller_freq_hz, doMotorController);
+  setupTimerCallback(publish_raw_odom_freq_hz, doPublishRawOdom);
+  setupTimerCallback(publish_raw_imu_freq_hz, doPublishRawImu);
+  setupTimerCallback(publish_bumper_info_freq_hz, doPublishBumpers);
+  setupTimerCallback(publish_teensy_debug_info_freq_hz, doTeensyDebug);
+  setupTimerCallback(BLINK_FREQ_HZ, doBlink);

   ros::Time current_time = ros_nh.now();
-  ros_raw_odom_msg.header.frame_id = ros_odom_header_frame_id;
-  ros_raw_odom_msg.child_frame_id = ros_odom_child_frame_id;
+  ros_raw_odom_msg.header.frame_id = "/odom";
+  ros_raw_odom_msg.child_frame_id = "/base_link";
+  ros_bumper_left_msg.header.frame_id = "/bumper_left";
+  ros_bumper_right_msg.header.frame_id = "/bumper_right";
   last_cmd_vel_time = current_time;
   last_encoder_read_time = current_time;
   encoder_left_pos = 0;
@@ -280,7 +284,7 @@
   setReferenceVelocity(vl / wheel_radius, vr / wheel_radius);
 }

-void doMotorController() {
+void doMotorController(void) {
   // Get the current wheel angular velocity
   double sensed_wl = getAngularVelocityFromSamples(samples_wl);
   double sensed_wr = getAngularVelocityFromSamples(samples_wr);
@@ -300,7 +304,7 @@
  * the difference with the previous value from the encoders
  * to calculate the angular velocity of each wheel.
  */
-void doReadEncoders() {
+void doReadEncoders(void) {
   ros::Time current_time = ros_nh.now();
   long new_encoder_left_pos = encoder_left.read();
   long new_encoder_right_pos = encoder_right.read();
@@ -322,7 +326,7 @@
 /*
  * Publish raw odometry to ros.
  */
-void doPublishRawOdom() {
+void doPublishRawOdom(void) {
   ros::Time current_time = ros_nh.now();
   static ros::Time last_raw_odom_publish_time(current_time);

@@ -422,7 +426,7 @@
 /*
  * Publish imu data to ros.
  */
-void doPublishRawImu() {
+void doPublishRawImu(void) {
   ros::Time current_time = ros_nh.now();
   imu.read();
   mag.read();
@@ -436,6 +440,45 @@
   ros_raw_imu_msg.magnetometer = convertMagnetometer(mag);

   ros_raw_imu_pub.publish(&ros_raw_imu_msg);
+}
+
+/*
+ * Publish bumper data to ros.
+ */
+void doPublishBumpers(void) {
+  // TODO(mwomack): Get readings from robot
+  static const int MIN_RAW_LEFT_BUMPER(650);
+  static const int MAX_RAW_LEFT_BUMPER(450);
+  static const double RANGE_RAW_LEFT_BUMPER(MAX_RAW_LEFT_BUMPER - MIN_RAW_LEFT_BUMPER);
+  static const double MAX_FORCE_LEFT_BUMPER(1.0);
+  static const int MIN_RAW_RIGHT_BUMPER(650);
+  static const int MAX_RAW_RIGHT_BUMPER(450);
+  static const double RANGE_RAW_RIGHT_BUMPER(MAX_RAW_RIGHT_BUMPER - MIN_RAW_RIGHT_BUMPER);
+  static const double MAX_FORCE_RIGHT_BUMPER(1.0);
+
+  ros::Time current_time = ros_nh.now();
+
+  int rawBumperLeft = analogRead(BUMPER_LEFT_PIN);
+  int rawBumperRight = analogRead(BUMPER_RIGHT_PIN);
+
+
+  double bumperLeft = MAX_FORCE_LEFT_BUMPER
+                        * ((rawBumperLeft - MIN_RAW_LEFT_BUMPER) / RANGE_RAW_LEFT_BUMPER);
+  double bumperRight = MAX_FORCE_RIGHT_BUMPER
+                        * ((rawBumperRight - MIN_RAW_RIGHT_BUMPER) / RANGE_RAW_RIGHT_BUMPER);
+
+  ros_bumper_left_msg.header.stamp = current_time;
+  ros_bumper_left_msg.min_value = 0.0;
+  ros_bumper_left_msg.max_value = MAX_FORCE_LEFT_BUMPER;
+  ros_bumper_left_msg.value = bumperLeft;
+
+  ros_bumper_right_msg.header.stamp = current_time;
+  ros_bumper_right_msg.min_value = 0.0;
+  ros_bumper_right_msg.max_value = MAX_FORCE_RIGHT_BUMPER;
+  ros_bumper_right_msg.value = bumperRight;
+
+  ros_raw_imu_pub.publish(&ros_bumper_left_msg);
+  ros_raw_imu_pub.publish(&ros_bumper_right_msg);
 }

 /*
@@ -508,25 +551,6 @@
     blink_state = LOW;
   }
   digitalWrite(BLINK_PIN, blink_state);
-}
-
-void doBumperDebug() {
-  // Read the bumper sensors
-  snprintf(debug_str, sizeof(debug_str),
-    "L: %d    R: %d",
-    analogRead(BUMPER_LEFT_PIN),
-    analogRead(BUMPER_RIGHT_PIN));
-  ros_debug_msg.data = debug_str;
-  ros_bumper_debug_pub.publish(&ros_debug_msg);
-}
-
-void doEncoderDebug() {
-  // Read the encoders
-  snprintf(debug_str, sizeof(debug_str), "L: %ld    R: %ld",
-    encoder_left.read(),
-    encoder_right.read());
-  ros_debug_msg.data = debug_str;
-  ros_encoder_debug_pub.publish(&ros_debug_msg);
 }

 void doTeensyDebug() {
@@ -546,14 +570,14 @@
   ros_teensy_debug_pub.publish(&teensy_debug_msg);
 }

-/*
- * 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);
+/**
+ * Sets up a callback that is called at the
+ * given frequency.
+ */
+void setupTimerCallback(int callback_freq_hz, void (*callback)(void)) {
+  // Convert frequency in hertz to milliseconds
+  int callback_millis = (1000/callback_freq_hz);
+  timer.every(callback_millis, callback);
 }

 /**


rewritten Weather Printing functions and added a sendWeather() function for SMS reporting to server

--- mwsSIMDUINO/mwsSIMDUINO.ino
+++ mwsSIMDUINO/mwsSIMDUINO.ino
@@ -151,6 +151,7 @@
   //Serial.println(sendData("AT+CMGS=\"+33785351655\"", 1000, DEBUG));    //Start accepting the text for the message Stef
   //*//Serial.println(sendData("AT+CMGS=\"+94774496950\"", 1000, DEBUG));    //Start accepting the text for the message Dave
   //Serial.println(sendData("AT+CMGS=\"+94716494873\"", 1000, DEBUG));    //Start accepting the text for the message YannLK
+  //Serial.println(sendData("AT+CMGS=\"+94716494873\"", 1000, DEBUG));    //Start accepting the text for the message SIRI_SA#4
   //*//Serial.println(sendData("\"Yann test mws simduino setup\"", 1000, DEBUG));   //The text for the message
   //*//ss.write(0x1A);
   delay(1000);
@@ -194,22 +195,12 @@
   lastSecond = millis();

   //CONFIRM BY SMS Lat/Long ARE ACQUIRED
-  //Serial.print(sendData("AT+CPIN?", 1000, DEBUG));
-  //Serial.print(sendData("AT+CPIN?", 1000, DEBUG));
-  //delay(5000); //WAIT FOR SIM808
   Serial.print(sendData(" ", 2000, DEBUG));
   Serial.println(sendData("AT+CMGF=1", 1000, true));
-  //Serial.println(sendData("AT+CSCA=\"+9477000003\"", 1000, DEBUG));  //Setting for the SMS Message center number,
-  //Note that when specifying a String of characters " is entered as \"
-  //Serial.println(sendData("AT+CMGS=\"+33785351655\"", 1000, DEBUG));    //Start accepting the text for the message Stef
-  Serial.println(sendData("AT+CMGS=\"+94774496950\"", 1000, DEBUG));    //Start accepting the text for the message Dave
-  //Serial.println(sendData("AT+CMGS=\"+94716494873\"", 1000, DEBUG));    //Start accepting the text for the message YannLK
-  Serial.println(sendData("\"GPS lat/Long coordinates acquired\"", 1000, DEBUG));   //The text for the message
+  Serial.println(sendData("AT+CMGS=\"+94773260142\"", 1000, DEBUG));    //Start accepting the text for the message SIRI_SA#4
+  Serial.println(sendData("\"SIMDuino: GPS lat/Long coordinates acquired\"", 1000, DEBUG));   //The text for the message
   ss.write(0x1A);
   delay(1000);
-  //DEBUG
-  //Serial.println(freeMemory());
-
 }

 void loop()
@@ -273,18 +264,10 @@
       printWeather();
       //Send daily rain report at 2AM GMT
       if (gpshour == 2) {
-        sprintf(sz, "\"%d : %.3f mm/d\"", STATION_NAME, dailyrainin); //[4]
-        //CONFIRM BY SMS Lat/Long ARE ACQUIRED
-        //Serial.print(sendData("AT+CPIN?", 1000, DEBUG));
-        //Serial.print(sendData("AT+CPIN?", 1000, DEBUG));
-        //delay(5000); //WAIT FOR SIM808
+        sprintf(sz, "\"%d (%.3f .3%f) : %.3f mm/d\"", STATION_NAME, gpslng, gpslat, dailyrainin); //[4]
         Serial.print(sendData(" ", 2000, DEBUG));
         Serial.println(sendData("AT+CMGF=1", 1000, true));
-        //Serial.println(sendData("AT+CSCA=\"+9477000003\"", 1000, DEBUG));  //Setting for the SMS Message center number,
-        //Note that when specifying a String of characters " is entered as \"
-        //Serial.println(sendData("AT+CMGS=\"+33785351655\"", 1000, DEBUG));    //Start accepting the text for the message Stef
-        Serial.println(sendData("AT+CMGS=\"+94774496950\"", 1000, DEBUG));    //Start accepting the text for the message Dave
-        //Serial.println(sendData("AT+CMGS=\"+94716494873\"", 1000, DEBUG));    //Start accepting the text for the message YannLK
+        Serial.println(sendData("AT+CMGS=\"+94773260142\"", 1000, DEBUG));    //Start accepting the text for the message SIRI_SA#4
         Serial.println(sendData(sz, 1000, DEBUG));   //The text for the message
         ss.write(0x1A);
         delay(1000);
@@ -295,17 +278,9 @@
       }
       if (rainin > 10.0) {
         sprintf(sz, "\"%d : %.3f mm/h\"", STATION_NAME, rainin); //[4]
-        //CONFIRM BY SMS Lat/Long ARE ACQUIRED
-        //Serial.print(sendData("AT+CPIN?", 1000, DEBUG));
-        //Serial.print(sendData("AT+CPIN?", 1000, DEBUG));
-        //delay(5000); //WAIT FOR SIM808
         Serial.print(sendData(" ", 2000, DEBUG));
         Serial.println(sendData("AT+CMGF=1", 1000, true));
-        //Serial.println(sendData("AT+CSCA=\"+9477000003\"", 1000, DEBUG));  //Setting for the SMS Message center number,
-        //Note that when specifying a String of characters " is entered as \"
-        //Serial.println(sendData("AT+CMGS=\"+33785351655\"", 1000, DEBUG));    //Start accepting the text for the message Stef
-        Serial.println(sendData("AT+CMGS=\"+94774496950\"", 1000, DEBUG));    //Start accepting the text for the message Dave
-        //Serial.println(sendData("AT+CMGS=\"+94716494873\"", 1000, DEBUG));    //Start accepting the text for the message YannLK
+        Serial.println(sendData("AT+CMGS=\"+94773260142\"", 1000, DEBUG));    //Start accepting the text for the message SIRI_SA#4
         Serial.println(sendData(sz, 1000, DEBUG));   //The text for the message
         ss.write(0x1A);
         delay(1000);
@@ -625,70 +600,68 @@

 //Prints the various variables directly to the port
-//I don't like the way this function is written but Arduino doesn't support floats under sprintf
+char mkWeatherString() {
+  char sz[200];
+  dtostrf(gpslng, 6, 6, &sz[strlen(sz)]);
+  strcpy(sz, ",");
+  dtostrf(gpslat, 6, 6, &sz[strlen(sz)]);
+  strcpy(sz, ",");
+  dtostrf(gpsalt, 6, 6, &sz[strlen(sz)]);
+  sprintf(sz, ",%d,", gpssat);
+  sprintf(sz, "%02d-%02d-%02d,", gpsyear, gpsmonth, gpsday);//[4]
+  sprintf(sz, "%02d:%02d:%02d,", gpshour, gpsminute, gpssecond);//[5]
+  sprintf(sz, "%d,", get_wind_direction());
+  dtostrf(get_wind_speed(), 4, 2, &sz[strlen(sz)]);
+  strcpy(sz, ",");
+  dtostrf(windgustms, 4, 2, &sz[strlen(sz)]);
+  sprintf(sz, ",%d,", windgustdir);
+  dtostrf(windspdms_avg2m, 4, 2, &sz[strlen(sz)]);
+  sprintf(sz, ",%d,", winddir_avg2m);
+  dtostrf(windgustms_10m, 4, 2, &sz[strlen(sz)]);
+  sprintf(sz, ",%d,", windgustdir_10m);
+  dtostrf(humidity, 4, 2, &sz[strlen(sz)]);
+  strcpy(sz, ",");
+  dtostrf(tempf, 4, 2, &sz[strlen(sz)]);
+  strcpy(sz, ",");
+  dtostrf(rainin, 4, 2, &sz[strlen(sz)]);
+  strcpy(sz, ",");
+  dtostrf(dailyrainin, 4, 2, &sz[strlen(sz)]);
+  strcpy(sz, ",");
+  dtostrf(pressure, 6, 6, &sz[strlen(sz)]);
+  strcpy(sz, ",");
+  dtostrf(batt_lvl, 4, 2, &sz[strlen(sz)]);
+  strcpy(sz, ",");
+  dtostrf(light_lvl, 4, 2, &sz[strlen(sz)]);
+  strcpy(sz, "\n");
+  return (sz);
+}
+
 void printWeather()
 {
   calcWeather(); //Go calc all the various sensors
-
-  Serial.println();
-  Serial.print(gpslng, 6);//[0]
-  Serial.print(",");
-  Serial.print(gpslat, 6);//[1]
-  Serial.print(",");
-  Serial.print(gpsalt);//[2]
-  Serial.print(",");
-  Serial.print(gpssat);//[3]
-
-  char sz[32];
-  Serial.print(",");
-  sprintf(sz, "%02d-%02d-%02d", gpsyear, gpsmonth, gpsday);//[4]
-  Serial.print(sz);
-
-  Serial.print(",");
-  sprintf(sz, "%02d:%02d:%02d", gpshour, gpsminute, gpssecond);//[5]
-  Serial.print(sz);
-
-  Serial.print(",");
-  Serial.print(get_wind_direction());//[6]
-  Serial.print(",");
-  Serial.print(get_wind_speed(), 1);//[7]
-  Serial.print(",");
-  Serial.print(windgustms, 1);//[8]
-  Serial.print(",");
-  Serial.print(windgustdir);//[9]
-  Serial.print(",");
-  Serial.print(windspdms_avg2m, 1);//[10]
-  Serial.print(",");
-  Serial.print(winddir_avg2m);//[11]
-  Serial.print(",");
-  Serial.print(windgustms_10m, 1);//[12]
-  Serial.print(",");
-  Serial.print(windgustdir_10m);//[13]
-  Serial.print(",");
-  Serial.print(humidity, 1);//[14]
-  Serial.print(",");
-  Serial.print(tempf, 1);//[15] Celsius
-  Serial.print(",");
-  Serial.print(rainin, 3);//[16] hourly
-  Serial.print(",");
-  Serial.print(dailyrainin, 3);//[17]
-  Serial.print(",");
-  Serial.print(pressure, 2);//[20]
-  Serial.print(",");
-  Serial.print(batt_lvl, 2);//[21]
-  Serial.print(",");
-  Serial.print(light_lvl, 2);//[22]
-  Serial.print(",");
-}
-
-
-
-
-
-
-
-
-
-
-
-
+  Serial.print(mkWeatherString());
+}
+
+void sendWeather()
+{
+  calcWeather(); //Go calc all the various sensors
+  char sz[200];
+  strcpy(sz,mkWeatherString());
+  Serial.print(sendData(" ", 2000, DEBUG));
+  Serial.println(sendData("AT+CMGF=1", 1000, true));
+  Serial.println(sendData("AT+CMGS=\"+94773260142\"", 1000, DEBUG));    //Start accepting the text for the message SIRI_SA#4
+  Serial.println(sendData(sz, 1000, DEBUG));   //The text for the message
+  ss.write(0x1A);
+  delay(1000);
+}
+
+
+
+
+
+
+
+
+
+
+


- Increased temperature thresholds - adjusted ADC values to 9V power supply (now stable voltage) - removed 5V measurements - added startup sequence - increased Serial speed to 57600 baud - fixed json serial output format

--- arduino/repeaterControl/repeaterControl.ino
+++ arduino/repeaterControl/repeaterControl.ino
@@ -9,15 +9,15 @@

 //mapping of Output Pins
 const int ONBOARD_LED = 13;
-const int RELAIS_12V = 11;
-const int RELAIS_5V = 10;
-const int RELAIS_230V_PHASE = 9;
-const int RELAIS_230V_NEUTRAL = 8;
+const int RELAIS_12V = 9;
+const int RELAIS_12V_GND = 8;
+const int RELAIS_230V_PHASE = 11;
+const int RELAIS_230V_NEUTRAL = 10;

 //mapping of Input Pins
 const int ONE_WIRE_BUS = 12;
 const int ADC_12V = 0;            //ADC
-const int ADC_5V = 1;             //ADC
+const int ADC_TBD = 1;             //ADC
 const int ADC_VSWR_FORWARD = 2;      //ADC
 const int ADC_VSWR_RETURN = 3;       //ADC

@@ -65,8 +65,8 @@
 float temperatureShack = -999;

 // Set the temperature limits when equipment (relais) will be shut off
-const int TEMP_TX_LIMIT_HIGH = 45; //deg Celcius - upper hysteresis level
-const int TEMP_TX_LIMIT_LOW = 40; //deg Celcius -  lower hysteresis level
+const int TEMP_TX_LIMIT_HIGH = 60; //deg Celcius - upper hysteresis level
+const int TEMP_TX_LIMIT_LOW = 55; //deg Celcius -  lower hysteresis level

 const int TEMP_CABINET_LIMIT_HIGH = 45; //deg Celcius - upper hysteresis level
 const int TEMP_CABINET_LIMIT_LOW = 40; //deg Celcius -  lower hysteresis level
@@ -99,28 +99,25 @@
 //******************************************************************

 //define limits
-const int ADC_12V_LOWER_LIMIT_LOW = 452;  // 10,4V lower hysteresis
-const int ADC_12V_LOWER_LIMIT_HIGH = 484;  // 11,0V upper hysteresis
-const int ADC_12V_UPPER_LIMIT_LOW = 652; //14,8V lower hysteresis
-const int ADC_12V_UPPER_LIMIT_HIGH = 681; //15,5V upper hysteresis
-
-int adc_5v_upper_limit = 587;  // 5.5V
-int adc_5v_lower_limit = 480;  // 4.5V
+const int ADC_12V_LOWER_LIMIT_LOW = 432;  // 10,4V lower hysteresis
+const int ADC_12V_LOWER_LIMIT_HIGH = 459;  // 11,0V upper hysteresis
+const int ADC_12V_UPPER_LIMIT_LOW = 615; //14,8V lower hysteresis
+const int ADC_12V_UPPER_LIMIT_HIGH = 645; //15,5V upper hysteresis

 const float SWR_LIMIT = 3;

 // Variables set True in case limits are exeeded
 bool error_12v = false;
-bool error_5v = false;
 bool error_230v = false;
 bool error_vswr = false;

-const int ADC_READINGS = 3;          // number of ADC samples used for averaging
+const int ADC_READINGS = 4;          // number of ADC samples used for averaging
 int adc_index = 0;                  // pointer to the current reading in the arrays
+
+int startup = true;                // startup phase

 //arrays to store ADC values
 int adc_12v[ADC_READINGS];
-int adc_5v[ADC_READINGS];
 int adc_vswr_forward[ADC_READINGS];
 int adc_vswr_return[ADC_READINGS];

@@ -132,13 +129,11 @@

 //variables needed to calculate average
 int adc_12v_total = 0;
-int adc_5v_total = 0;
 int adc_vswr_forward_total = 0;
 int adc_vswr_return_total = 0;

 // average values
 int adc_12v_average = 0;
-int adc_5v_average = 0;
 int adc_vswr_forward_average = 0;
 int adc_vswr_return_average = 0;

@@ -148,7 +143,6 @@

 //status of output pins
 bool relais_12v = true;
-bool relais_5v = true;
 bool relais_230v_phase = true;
 bool relais_230v_neutral = true;
 bool onboardLedStatus = false;
@@ -158,7 +152,6 @@
 // Remote control status tracking variables
 //******************************************************************
 bool remote_12v_off = false;
-bool remote_5v_off = false;
 bool remote_230v_off = false;

@@ -169,6 +162,7 @@
 // Counters
 int irq_temp_counter = 0; //pre-scaler for Timer1 -> temperature measurement routine
 int irq_led_blink_counter = 0; //pre-scaler for Timer1 -> status LED blinking
+int irq_startup_counter = 0; //pre-scaler for Timer1 -> startup phase countdown
 int irq_swr_counter = 0; //pre-scaler for Timer1 -> SWR Measurement

@@ -184,12 +178,12 @@

   pinMode(ONBOARD_LED, OUTPUT);
   pinMode(RELAIS_12V, OUTPUT);
-  pinMode(RELAIS_5V, OUTPUT);
+  pinMode(RELAIS_12V_GND, OUTPUT);
   pinMode(RELAIS_230V_PHASE, OUTPUT);
   pinMode(RELAIS_230V_NEUTRAL, OUTPUT);

   //init serial port
-  Serial.begin(9600);
+  Serial.begin(57600);

   if (sensors.isConnected(SENSOR_TX)){
     sensors.getAddress(SENSOR_TX, 0);
@@ -208,13 +202,12 @@

   for (int thisReading = 0; thisReading < ADC_READINGS; thisReading++){
     adc_12v[thisReading] = 0;
-    adc_5v[thisReading] = 0;
     adc_vswr_forward[thisReading] = 0;
     adc_vswr_return[thisReading] = 0;
   }

   Timer1.initialize(50000); //timer Interrupt every 20ms
-  Timer1.attachInterrupt(checkLimits); //bind function to timer interrupt
+
 }

 //******************************************************************
@@ -264,18 +257,15 @@
 void getADCValues(void){
   //substract the last reading
   adc_12v_total -= adc_12v[adc_index];
-  adc_5v_total -= adc_5v[adc_index];
   adc_vswr_forward_total -= adc_vswr_forward[adc_index];
   adc_vswr_return_total -= adc_vswr_return[adc_index];

   adc_12v[adc_index] = analogRead(ADC_12V);
-  adc_5v[adc_index] = analogRead(ADC_5V);
   adc_vswr_forward[adc_index] = analogRead(ADC_VSWR_FORWARD);
   adc_vswr_return[adc_index] = analogRead(ADC_VSWR_RETURN);

   adc_12v_total += adc_12v[adc_index];
-  adc_5v_total += adc_5v[adc_index];
   adc_vswr_forward_total += adc_vswr_forward[adc_index];
   adc_vswr_return_total += adc_vswr_return[adc_index];

@@ -286,7 +276,6 @@
   }

   adc_12v_average = adc_12v_total / ADC_READINGS;
-  adc_5v_average = adc_5v_total / ADC_READINGS;
   adc_vswr_forward_average = adc_vswr_forward_total / ADC_READINGS;
   adc_vswr_return_average = adc_vswr_return_total / ADC_READINGS;
 }
@@ -294,17 +283,14 @@
 void setRelais12v(bool state){
   if ((state == true) && (overTemperatureTx == false) && (overTemperatureCabinet == false) && (remote_12v_off == false) && (error_vswr == false) && (error_12v == false)){
     digitalWrite(RELAIS_12V, true);
+    digitalWrite(RELAIS_12V_GND, true);
     relais_12v = true;
   }
   if (state == false){
     digitalWrite(RELAIS_12V, false);
+    digitalWrite(RELAIS_12V_GND, false);
     relais_12v = false;
   }
-}
-
-void setRelais5v(bool state){
-  digitalWrite(RELAIS_5V, state);
-  relais_5v = state;
 }

 void setRelais230v(bool state){
@@ -350,6 +336,13 @@
   }

+  //countdown timer for startup phase ... approx 2 secs
+  if (irq_startup_counter >= 100){
+    startup = false;
+  }
+  else{
+    irq_startup_counter += 1;
+  }

@@ -359,25 +352,23 @@

   //Handle 12V ADC
   if ((adc_12v_average > ADC_12V_UPPER_LIMIT_HIGH) || (adc_12v_average < ADC_12V_LOWER_LIMIT_LOW)){
-    error_12v = true;
-    setRelais12v(false);
+    if (startup == false){  //during startup phase do not turn off relais
+      error_12v = true;
+      setRelais12v(false);
+    }
   }
   if((adc_12v_average < ADC_12V_UPPER_LIMIT_LOW) && (adc_12v_average > ADC_12V_LOWER_LIMIT_HIGH)){
     error_12v = false;
     setRelais12v(true);
   }
-
-  //Handle 5V ADC
-  if((adc_5v_average > adc_5v_upper_limit) || (adc_5v_average < adc_5v_lower_limit)){
-    // do smth
-  }
+

   //Handle Bad SWR
-  if (irq_swr_counter >= 5){ //check approx every 100ms
+  if (irq_swr_counter >= 100){ //check approx every 2s
     float mySWR = calcSWR();
     if (swr_voltage_forward > 50){  //only check SWR if transmitting - power applied
-      vswr = mySWR;
+      vswr = mySWR; // write into global variable
       if(abs(vswr) >= 3){
         setRelais12v(false);
         error_vswr = true;
@@ -393,8 +384,6 @@
     irq_swr_counter+=1;
   }

-
-

@@ -408,7 +397,7 @@
     //Handle Transmitter Temperature
     if (temperature_tx_average >= TEMP_TX_LIMIT_HIGH){
       overTemperatureTx = true;  //needed to ensure that ADC doesn't enable the 12V again
-      relais_12v = false;
+      setRelais12v(false);
     }
     if (temperature_tx_average <= TEMP_TX_LIMIT_LOW){
       overTemperatureTx = false;
@@ -466,21 +455,19 @@
 void printTemperatures(void){

-  Serial.print("[");
-
-  Serial.print("{'tx': ");
-  Serial.print(temperatureTx);
-  Serial.print("},");
-
-  Serial.print("{'cabinet': ");
-  Serial.print(temperatureCabinet);
-  Serial.print("},");
-
-  Serial.print("{'shack': ");
-  Serial.print(temperatureShack);
-  Serial.print("}");
-
-  Serial.println("]");
+  Serial.print("{");
+
+  Serial.print("\"tx\":");
+  printDouble(temperature_tx_average, 100);
+  Serial.print(", ");
+
+  Serial.print("\"cabinet\":");
+  printDouble(temperature_cabinet_average, 100);
+  Serial.print(", ");
+
+  Serial.print("\"shack\":");
+  printDouble(temperature_shack_average, 100);
+  Serial.println("}");
 }

@@ -489,18 +476,14 @@

   Serial.print("{");

-  Serial.print("\"adc_12v\": ");
+  Serial.print("\"adc_12v\":");

-  printDouble((double)adc_12v_average/1024*23.78, 100);  //10bit 22k:4,7k voltage divider to cover 0...25V
-  Serial.print(",");
-
-
-  Serial.print("\"adc_5v\": ");
-  printDouble((double)adc_5v_average/1024*9.6, 100);  //10bit 5k:5k voltage devider to cover 0...10V
-  Serial.print(",");
-
-  Serial.print("\"vswr\": ");
-  printDouble(vswr, 100);
+  printDouble((double)adc_12v_average/1024*23.78+0.35, 100);  //10bit 22k:4,7k voltage divider to cover 0...25V
+  Serial.print(", ");
+
+
+  Serial.print("\"vswr\":");
+  printDouble(abs(vswr), 100);

   Serial.println("}");

@@ -508,90 +491,61 @@

 void printStatus(void){

-  Serial.print("[");
-
-  Serial.print("{'tx_overheat': ");
+  Serial.print("{");
+
+  Serial.print("\"tx_overheat\":");
   if(overTemperatureTx){
     Serial.print("true");
   }
   else{
     Serial.print("false");
   }
-  Serial.print("},");
-
-  Serial.print("{'cabinet_overheat': ");
+  Serial.print(", ");
+
+  Serial.print("\"cabinet_overheat\":");
   if(overTemperatureCabinet){
     Serial.print("true");
   }
   else{
     Serial.print("false");
   }
-  Serial.print("}");
-
-  Serial.print("{'error_12v': ");
+  Serial.print(", ");
+
+  Serial.print("\"error_12v\":");
   if(error_12v){
     Serial.print("true");
   }
   else{
     Serial.print("false");
   }
-  Serial.print("},");
-
-
-  Serial.print("{'error_5v': ");
-  if(error_5v){
-    Serial.print("true");
-  }
-  else{
-    Serial.print("false");
-  }  Serial.print("},");
-
-  Serial.print("{'error_vswr': ");
+  Serial.print(", ");
+
+  Serial.print("\"error_vswr\":");
   if(error_vswr){
     Serial.print("true");
   }
   else{
     Serial.print("false");
-  }  Serial.print("},");
-
-
-  Serial.print("{'12v_relais': ");
+  }  Serial.print(", ");
+
+
+  Serial.print("\"12v_relais\":");
   if(relais_12v){
     Serial.print("true");
   }
   else{
     Serial.print("false");
   }
-  Serial.print("},");
-
-  Serial.print("{'relais_5v': ");
-  if(relais_5v){
+  Serial.print(", ");
+
+  Serial.print("\"relais_230v\":");
+  if(relais_230v_phase){
     Serial.print("true");
   }
   else{
     Serial.print("false");
   }
-  Serial.print("},");
-
-  Serial.print("{'relais_230v_phase': ");
-  if(relais_230v_phase){
-    Serial.print("true");
-  }
-  else{
-    Serial.print("false");
-  }
-  Serial.print("},");
-
-  Serial.print("{'relais_230v_neutral': ");
-  if(relais_230v_neutral){
-    Serial.print("true");
-  }
-  else{
-    Serial.print("false");
-  }
-  Serial.print("}");
-
-  Serial.println("]");
+  Serial.println("}");
 }

@@ -618,12 +572,13 @@
     case 'x':{
       switch(inBytes[1]){
         case '1': {
+          remote_12v_off = false;
+          error_vswr = false; // reset VSWR Error
           setRelais12v(true);
-          remote_12v_off = false;
           break;
         }
         case '0': {
-          if ((overTemperatureCabinet == false) && (overTemperatureTx == false) && (error_5v == false)){
+          if ((overTemperatureCabinet == false) && (overTemperatureTx == false)){
             setRelais12v(false);
             remote_12v_off = true;
             break;
@@ -632,26 +587,7 @@
       }
       break;
     }
-
-    //turn 5v on/off remotely
-    case 'y':{
-      switch(inBytes[1]){
-        case '1': {
-          setRelais5v(true);
-          remote_5v_off = false;
-          break;
-        }
-        case '0': {
-          if ((overTemperatureCabinet == false) && (overTemperatureTx == false) && (error_5v == false)){
-            setRelais5v(false);
-            remote_5v_off = true;
-            break;
-          }
-        }
-      }
-      break;
-    }
-
+
     //turn 230v on/off remotely
     case 'z':{
       switch(inBytes[1]){
@@ -682,19 +618,22 @@
 {
   //startup

-  //enable all relais on start
-  digitalWrite(RELAIS_12V, HIGH);
-  digitalWrite(RELAIS_5V, HIGH);
-  digitalWrite(RELAIS_230V_PHASE, HIGH);
-  digitalWrite(RELAIS_230V_NEUTRAL, HIGH);
-
-  getTemperature();
+  //enable all relais on start first 230V, then 12V
+  setRelais230v(true);
+  getTemperature();  // #1 (3 measurements needed due to averaging)
+  delay(2000);
+  getTemperature();  // #2
+  delay(2000);
+  getTemperature();  // #3
+  setRelais12v(true);
+  delay(4000);
+
+  Timer1.attachInterrupt(checkLimits); //bind function to timer interrupt
+
   char inBytes[20];
-
+
   //main Loop
   while(true){
-    Serial.println(adc_12v_average);
-    delay(400);

     //read commands comming through USB Serial Interface
     if (Serial.available() > 0){


update collision detect in EventsTest

update collision detect in EventsTest

--- arduino/libraries/VeloKey/examples/EventsTest/EventsTest.ino
+++ arduino/libraries/VeloKey/examples/EventsTest/EventsTest.ino
@@ -64,11 +64,13 @@
   }
   // now = millis();
   ball.move(dx, dy);
-  if (ball.collide(&player1)){
+  if (ball.collide(&player1) && dx < 0){
     Serial.println("ouch player 1");
+    dx *= -1;
   }
-  if (ball.collide(&player2)){
+  if (ball.collide(&player2) && dx > 0){
     Serial.println("ouch player 2");
+    dx *= -1;
   }
   player1.draw();
   player2.draw();


-Small fixes.

-Small fixes.

--- wifitask.ino
+++ wifitask.ino
@@ -27,7 +27,7 @@

 /* https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/src/WiFiSTA.h */

-    //WiFi.mode( WIFI_AP_STA );
+    WiFi.mode( WIFI_AP_STA );
     WiFi.beginSmartConfig();

     const time_t rebootTime = millis() + 60 * 5 * 1000; /* 5 min */
@@ -60,7 +60,7 @@
   ESP_ERROR_CHECK( tcpip_adapter_get_ip_info( TCPIP_ADAPTER_IF_STA, &ip_info ) );
   ESP_LOGI( TAG, "WiFi connected to %s", WiFi.SSID().c_str() );
   ESP_LOGI( TAG, "Local IP: %s", ip4addr_ntoa( &ip_info.ip ) );
-  ESP_LOGI( TAG, "%02x:%02x:%02x:%02x:%02x:%02x",mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
+  ESP_LOGI( TAG, "MAC: %02x:%02x:%02x:%02x:%02x:%02x",mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
   if ( xTftTaskHandle )
   {
     tft.invertDisplay( false );


Fixed WiFi not connecting.

Fixed WiFi not connecting.

--- wifitask.ino
+++ wifitask.ino
@@ -140,28 +140,30 @@
 /* https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/src/WiFiType.h */
 void waitForWifi()
 {
-  while ( WiFi.status() != WL_CONNECTED &&
-          WiFi.status() != WL_NO_SSID_AVAIL &&
-          WiFi.status() != WL_CONNECT_FAILED )
+  unsigned long timeOut = millis() + 10000;
+  while ( !WiFi.isConnected() && millis() < timeOut )
   {
-    tft.print( "." );
+    if ( xTftTaskHandle )
+    {
+      tft.print( "." );
+    }
     vTaskDelay( 500 / portTICK_PERIOD_MS );
   }
 }
 /*
-  void WiFiEvent( WiFiEvent_t event )
-  {
+void WiFiEvent( WiFiEvent_t event )
+{
   switch ( event )
   {
     case SYSTEM_EVENT_AP_START:
-      //ESP_LOGI( TAG, "AP Started");
+      ESP_LOGI( TAG, "AP Started");
       //WiFi.softAPsetHostname(AP_SSID);
       break;
     case SYSTEM_EVENT_AP_STOP:
       ESP_LOGI( TAG, "AP Stopped");
       break;
     case SYSTEM_EVENT_STA_START:
-      //ESP_LOGI( TAG, "STA Started");
+      ESP_LOGI( TAG, "STA Started");
       //WiFi.setHostname( DEFAULT_HOSTNAME_PREFIX.c_str( );
       break;
     case SYSTEM_EVENT_STA_CONNECTED:
@@ -169,7 +171,7 @@
       //WiFi.enableIpV6();
       break;
     case SYSTEM_EVENT_AP_STA_GOT_IP6:
-      //ESP_LOGI( TAG, "STA IPv6: ");
+      ESP_LOGI( TAG, "STA IPv6: ");
       //ESP_LOGI( TAG, "%s", WiFi.localIPv6().toString());
       break;
     case SYSTEM_EVENT_STA_GOT_IP:
@@ -185,5 +187,5 @@
     default:
       break;
   }
-  }
+}
 */


minor fix

minor fix

--- nodeMCU/plant/functions.ino
+++ nodeMCU/plant/functions.ino
@@ -30,7 +30,7 @@
      Serial.println("HTTP/1.0 \n\n");

      client.println();
-     client.stop();
+

    delay(1000);


Arduino uses ambient temperature as a threshold against the object temperature.

Forgot this sensor had that ability...

--- arduino/impetus/impetus.ino
+++ arduino/impetus/impetus.ino
@@ -6,7 +6,7 @@
 int mphonePin = 0;
 int buzzPin = 10;
 int cycle = 0, vol = 0;
-double temp = 0, ref = 0;
+double temp = 0;
 boolean flash = false, sample = false, alarm = false, buzz = LOW;

 void setup(){
@@ -22,11 +22,7 @@
   i2c_init(); //Initialise the i2c bus
   PORTC = (1 << PORTC4) | (1 << PORTC5);//enable pullups

-  for (int i = 0; i < 10; i++) {
-    ref += readTemp();
-    delay(1000);
-  }
-  ref /= 10;
+  float ref = readAmb();

   display.write((int) ref / 10);
   display.write((int) ref % 10);
@@ -55,14 +51,14 @@
   }
 }

-float readTemp(){
+float mlxRead(byte loc){
   int dev = 0x5A<<1;
   int data_low = 0;
   int data_high = 0;
   int pec = 0;

   i2c_start_wait(dev+I2C_WRITE);
-  i2c_write(0x07);
+  i2c_write(loc);

   // read
   i2c_rep_start(dev+I2C_READ);
@@ -86,6 +82,14 @@
   return fahrenheit;
 }

+float readTemp() {
+  return mlxRead(0x07);
+}
+
+float readAmb() {
+  return mlxRead(0x06);
+}
+
 int readVol() {
   int readings[50], minR = 1023, maxR = 0;
   for (int i = 0; i < 50; i++) {
@@ -103,10 +107,10 @@

 void loop() {
   if (sample) {
-    ref = readTemp();
+    int tt = readTemp();
     int tv = readVol();
-    if (ref > temp)
-      temp = ref;
+    if (tt > temp)
+      temp = tt;
     if (tv > vol)
       vol = tv;
     cycle++;
@@ -115,16 +119,17 @@
       if (Serial) {
         Serial.print(temp);
         Serial.print(" ");
+        Serial.print(readAmb());
+        Serial.print(" ");
         Serial.println(vol);
       }
       temp = 0;
       vol = 0;
     }
   } else {
-
-    if (alarm && readTemp() <= ref + 5)
+    if (alarm && readTemp() <= readAmb() + 5)
       cycle++;
-    else if (!alarm && readTemp() > ref + 5)
+    else if (!alarm && readTemp() > readAmb() + 5)
       cycle++;
     else
       cycle = 0;


moved mqtt code and debug to mqtt.ino

moved mqtt code and debug to mqtt.ino

--- src/WiFiSensor/WiFiSensor.ino
+++ src/WiFiSensor/WiFiSensor.ino
@@ -151,7 +151,7 @@
           Serial.println("Unable to connect to MQTT Server");
         }else{
     			// Connect to MQTT Server
-    			client.connect(mqttclientname.c_str(), mqttusername.c_str(), mqttpassword.c_str() );
+    			//client.connect(mqttclientname.c_str(), mqttusername.c_str(), mqttpassword.c_str() );
     			//Following is original
     			String topicname("sensors/");
     			topicname += String(sensorname);


clean up

clean up

--- hook___dail/hook___dail.ino
+++ hook___dail/hook___dail.ino
@@ -82,8 +82,7 @@
   Serial.println("0: stop the music");
   Serial.println();
   Serial.println();
-
-
+
   ///////////////////////////////////////////////////// SETUP BLUETOOTH
   // start our serial so we can send and recieve
   // information from the BT module
@@ -112,7 +111,6 @@
   //Initialize the MP3 Player Shield
   result = MP3player.begin();
   //check result, see readme for error codes.
-  }

   #if (0)
   // Typically not used by most shields, hence commented out.
@@ -122,6 +120,8 @@
     MP3player.ADMixerVol(-3);
   }
   #endif
+}
+

 void loop()
 {


removed duplicate print statements

removed duplicate print statements

--- code/arduino/main/aws_sketch/aws_sketch.ino
+++ code/arduino/main/aws_sketch/aws_sketch.ino
@@ -13,6 +13,7 @@
  *
  */

+#include <stdlib.h>
 #include <avr/wdt.h>
 #include <Wire.h>
 #include <DHT22.h>
@@ -24,7 +25,6 @@
 // @change pins and output modes
 #define DHT22_PIN 6
 #define AWS_NO_SERIAL 1
-#define AWS_NO_GSM 1

 // Analog pin A4(SDA),A5(SCL)
 Adafruit_BMP085 bmp;
@@ -58,6 +58,7 @@

 // return codes
 DHT22_ERROR_t dht22_code ;
+char* buffer ;

 void setup() {

@@ -65,6 +66,8 @@
     Serial.begin(9600);
 #endif

+    char tmp[1] = {'0' } ;
+    buffer = tmp ;
     // watchdog enabled
     wdt_enable(WDTO_8S);

@@ -85,9 +88,14 @@
     // try again
     if(timeStatus()!= timeSet) {
         // CLK error
-#if !defined(AWS_NO_SERIAL)
-        Serial.println("clock error");
-#endif
+        char error[] = "clock error" ;
+#if !defined(AWS_NO_SERIAL)
+        Serial.println(error);
+#endif
+#if !defined(AWS_NO_LCD)
+       lcd_one_liner(error);
+
+#endif
         for(;;);
     }

@@ -107,7 +115,7 @@
     micro_delay(20);
 #endif

-    Alarm.alarmRepeat(8,30,10, send_bulletin);
+    Alarm.alarmRepeat(21,55,10, send_bulletin);

 }

@@ -133,6 +141,8 @@

 void update_display() {

+    char output[33] ;
+    output[0] = 'T' ;
     // DHT22 pin needs 2 seconds
     micro_delay(250);
     dht22_code = myDHT22.readData();
@@ -140,13 +150,41 @@
     if(dht22_code == DHT_ERROR_NONE) {
         dht22_temp = myDHT22.getTemperatureC();
         humidity = myDHT22.getHumidity();
+        // print H and T into char buffer
+        dtostrf(dht22_temp,5,1,output+1);
+        output[6] = ' ' ;
+        output[7] = 'H' ;
+        dtostrf(humidity,4,1,output + 8);
+        output[12] = '%' ;
+        for(int i = 13 ; i < 16; i++) { output[i] = ' '; }

     } else {
-        // absurd value
-        dht22_temp = 9999.0 ;
-    }
-
+        output[1] = ' ';
+        output[2] = 'E';
+        output[3] = 'R';
+        output[4] = 'R';
+        output[5] = 'O';
+        output[6] = 'R';
+        for(int i = 7 ; i < 16; i++) { output[i] = ' '; }
+    }
+
+    output[16] = 'P' ;
     pressure = bmp.readPressure();
+    pressure = round(pressure/100.0) ;
+    sprintf(output+17,"%-5d",pressure);
+    output[22] = ' ';
+    output[23] = 'R';
+
+    // more rain in a day than cherapunji
+    // receives in a year!
+    sprintf(output+24,"%-5d",rain_counter);
+    for(int i = 29 ; i < 32; i++){ output[i] = ' ' ; }
+    // null
+    output[32] = '\0' ;
+
+    buffer = output ;
+
+

 #if !defined(AWS_NO_SERIAL)
     serial_output();
@@ -166,27 +204,12 @@
     gsmSerial.print("AT+CMGF=1\r");
     micro_delay(20);
     // @change sms number
-    gsmSerial.print("AT+CMGS=\"+91xxxyyyzzzz\"\r");
+    gsmSerial.print("AT+CMGS=\"+919886124428\"\r");
     micro_delay(20);
     // pat watchdog
     wdt_reset();
-
-    gsmSerial.print("Yuktix H");
-    if(dht22_code !=  DHT_ERROR_NONE) {
-        gsmSerial.println("ERR");
-        gsmSerial.print(dht22_code);
-
-    } else {
-        gsmSerial.println(humidity);
-        gsmSerial.print("T");
-        gsmSerial.print(dht22_temp);
-    }
-
-    gsmSerial.print(" P");
-    gsmSerial.print(pressure);
-    gsmSerial.print(" R");
-    gsmSerial.print(rain_counter);
-    gsmSerial.println();
+    for(int i = 0 ; i < 32 ;i++) { gsmSerial.print(buffer[i]); }
+
     gsmSerial.write(0x1A);
     micro_delay(100);
     // pat watchdog
@@ -213,60 +236,46 @@

 #if !defined(AWS_NO_SERIAL)
 void serial_output() {
-    Serial.print("Yuktix H");
-    if(dht22_code !=  DHT_ERROR_NONE) {
-        Serial.println("ERR");
-        Serial.print(dht22_code);
-
-    } else {
-        Serial.println(humidity);
-        Serial.print(" T");
-        Serial.print(dht22_temp);
-    }
-
-    Serial.print(" P");
-    Serial.print(pressure);
-    Serial.print(" R");
-    Serial.print(rain_counter);
-
-}
+    int hh = hour();
+    int mm = minute();
+    int ss = second();
+
+    char ts[9] ;
+    sprintf(ts,"%d:%d:%d",hh,mm,ss);
+    // time
+    Serial.println(ts);
+    // data
+    Serial.println(buffer);
+
+}
+
 #endif

 #if !defined(AWS_NO_LCD)
 void lcd_output() {

-    int t1 ;
-    int p1 ;
-    int h1 ;
-
     pinMode(lcd_pin, OUTPUT);
     digitalWrite(lcd_pin, HIGH);
     lcd.begin(16,2);
     lcd.clear();
     // line1
     lcd.setCursor(0,0);
-    lcd.print("YUKTIX H");
-    if(dht22_code !=  DHT_ERROR_NONE) {
-        lcd.print("ERR");
-        lcd.setCursor(0,1);
-        lcd.print(dht22_code);
-
-    } else {
-        h1 = round(humidity);
-        lcd.print(h1);
-        lcd.print("%");
-        lcd.setCursor(0,1);
-        lcd.print("T");
-        t1 = round(dht22_temp);
-        lcd.print(t1);
-    }
-
-    lcd.print(" P");
-    p1 = round(pressure/10.0);
-    lcd.print(p1);
-    lcd.print(" R");
-    lcd.print(rain_counter);
-}
+    for(int i = 0 ; i < 15; i++){ lcd.print(buffer[i]); }
+    lcd.setCursor(0,1);
+    for(int i = 16 ; i < 32; i++){ lcd.print(buffer[i]); }
+}
+
+void lcd_one_liner(char* str) {
+    pinMode(lcd_pin, OUTPUT);
+    digitalWrite(lcd_pin, HIGH);
+    lcd.begin(16,2);
+    lcd.clear();
+    // line1
+    lcd.setCursor(0,0);
+    lcd.print(str);
+
+}
+
 #endif

 void loop() {
@@ -278,3 +287,4 @@
     // alarm wont work w/o alarm delay
     Alarm.delay(1000);
 }
+


Add backsteer to drone radio drive

Add backsteer to drone radio drive

--- examples/DroneSimpleRadioDrive/DroneSimpleRadioDrive.ino
+++ examples/DroneSimpleRadioDrive/DroneSimpleRadioDrive.ino
@@ -1,16 +1,18 @@
 #include <MINDS-i-Drone.h>

-ServoGenerator::Servo drive, steer;
+ServoGenerator::Servo drive, steer, backsteer;

 void setup() {
   drive.attach(12 /* APM pin 1 */);
   steer.attach(11 /* APM pin 2 */);
+  backsteer.attach(8 /* APM pin 3 */);

   ServoGenerator::begin();

   //set the initial throttle/direction for the ESC/servo
   drive.write(90);
   steer.write(90);
+  backsteer.write(90);

   APMRadio::setup();
   Serial.begin(9600);
@@ -36,4 +38,5 @@

   drive.write( driveSig );
   steer.write( steerSig );
+  backsteer.write( 90 - steerSig );
 }


Add version & date

Add version & date

--- ArduinoMotionStairLights.ino
+++ ArduinoMotionStairLights.ino
@@ -1,8 +1,8 @@
 /*
  * Description: Motion activated stair lights.
  * Author: Dean Montgomery
- * Version: 0.6 (Beta)
- * Date: 2015-07-26
+ * Version: 1.0
+ * Date: Aug 8, 2015
  *
  * 2 PIR sesors at the top and bottom of the stairs.
  * WS28012B Addressable RGB lights - 2 LEDs on each stair - This spread out the strip of 30 and left 2-pairs for spare bulbs.


del debugIno

del debugIno

--- Atom_Node.ino
+++ Atom_Node.ino
@@ -34,16 +34,6 @@

 #include "NodeApp.h"
 #include "NodeCfg.h"
-
-#define __DebugIno      0
-
-#if __DebugIno
-#define __printIno(x)   __print(x)
-#define __printlnIno(x) __println(x)
-#else
-#define __printIno(x)
-#define __printlnIno(x)
-#endif

 unsigned char __GdtaUart[50];                   // uart data buff
 unsigned char __GdtaUartLen        = 0;         // uart data len


minor change 1

minor change 1

--- proj/hypercube/HCS/HCS.ino
+++ proj/hypercube/HCS/HCS.ino
@@ -76,7 +76,7 @@
 uint8_t gHue;

 // For animation switching, this number needs to be hard coded unforunately
-const uint8_t numAnimation = 10;
+const uint8_t numAnimation = 11;
 uint8_t iAnimCounter, oAnimCounter;
 boolean iAnimSwitch, oAnimSwitch; // Use this flag so that we fade the color palette into each animation
 uint8_t iAnimSwitchCount, oAnimSwitchCount; // Use this to count how many times we've faded to the


updated the LED array example so you can change the number of LEDs without changing the code in more than one spot

--- photoresistors/pcb_photoresistor_led_array_example/pcb_photoresistor_led_array_example.ino
+++ photoresistors/pcb_photoresistor_led_array_example/pcb_photoresistor_led_array_example.ino
@@ -12,84 +12,101 @@
 #define LED_ARRAY_ELEMENT_3 10
 #define LED_ARRAY_ELEMENT_4 11

+// Sample rate
+#define PHOTORESISTOR_SAMPLE_RATE_IN_MS 50
+
 static int ledArray[5] = {LED_ARRAY_ELEMENT_0, LED_ARRAY_ELEMENT_1, LED_ARRAY_ELEMENT_2, LED_ARRAY_ELEMENT_3, LED_ARRAY_ELEMENT_4};
-static const int ARRAY_SIZE = sizeof(ledArray) / sizeof(int);
+static const int NUM_OF_LEDS_IN_ARRAY = sizeof(ledArray) / sizeof(int);
+
+static const int LED_MIN_BRIGHTNESS = 0;
+static const int LED_MAX_BRIGHTNESS = 255;
+
+static const int PHOTORESISTOR_MIN_VALUE = 0;
+static const int PHOTORESISTOR_MAX_VALUE = 1023;
+
+static const int LED_RANGE = (LED_MAX_BRIGHTNESS - LED_MIN_BRIGHTNESS) + 1;
+static const int PHOTORESISTOR_RANGE = (PHOTORESISTOR_MAX_VALUE - PHOTORESISTOR_MIN_VALUE) + 1;
+
+static const int  PHOTORESISTOR_STEP = PHOTORESISTOR_RANGE / NUM_OF_LEDS_IN_ARRAY;
+static const float PHOTORESISTOR_TO_LED_MULTIPLIER = (float)LED_RANGE / (float)PHOTORESISTOR_STEP;

 void setup() {
   // Init the serial communications for debugging messages
   Serial.begin(9600);

+  Serial.print("Number of LEDs in the Array: "); Serial.println(NUM_OF_LEDS_IN_ARRAY);
+  Serial.print("LED Range: "); Serial.println(LED_RANGE);
+  Serial.print("Photoresistor Step: "); Serial.println(PHOTORESISTOR_STEP);
+  Serial.print("Photoresistor Range: "); Serial.println(PHOTORESISTOR_RANGE);
+  Serial.print("Multiplier: "); Serial.println(PHOTORESISTOR_TO_LED_MULTIPLIER);
+
   // Iterate over the array and set the PWM pins to output
-  for(int i = 0; i < ARRAY_SIZE; i++) {
+  for(int i = 0; i < NUM_OF_LEDS_IN_ARRAY; i++) {
     pinMode(ledArray[i], OUTPUT);
   }
 }

 void loop() {
   // *** Uncomment this line if the data line runs from A0 on the PCB to A0 on the Arduino
-  int brightness = readAnalogSensorPin();
+  int photoresistorAnalogValue = readAnalogSensorPin();

-  updateLedArray(brightness);
+  updateLedArray(photoresistorAnalogValue);

   // Add this delay so the output is trottled to something reasonable
-  delay(50);
+  delay(PHOTORESISTOR_SAMPLE_RATE_IN_MS);
 }

 int readAnalogSensorPin() {
   // Read the value on the Analog pin - represents the value from the photoresistor PCB. Values are
   // 0 (bright) to 1023 (dark)
-  int analogVal = analogRead(SENSOR_ANALONG_PIN);
-
-  Serial.println(analogVal);
-
-  return analogVal;
+  int photoresistorAnalogValue = analogRead(SENSOR_ANALONG_PIN);
+  return photoresistorAnalogValue;
 }

-void updateLedArray(int brightness) {
+void updateLedArray(int photoresistorAnalogValue) {
   // The PWM is 0-255, where 255 is 100% duty cycle and 0 is 0% duty cycle. The photoresistor is brightest when
-  // it is a analog value of 0, and darkest when it is 1023. There are more clever ways to do this than
-  // a straight up compare of the ranges, but this is clearer. If you want, you can look into bit shifting and
-  // masking to allow for dynamic array size without changing the algorithim, just the array size.
+  // it is a analog value of 0, and darkest when it is 1023.
+
+  // Invert the value to make the max the brightness value instead of 0 being the brightest
+  // Remember, a value of 0 (or min value set above) means no resistance and therefore means the room is bright
+  int brightness = PHOTORESISTOR_MAX_VALUE - photoresistorAnalogValue;

-
-  // Brightness values 820 - 1023 light up LED 0 and the others are off
-  // Brightness values 615 - 819 light up LEDs 0 and 1 and the others are off
-  // Brightness values 410 - 614 light up LEDs 0-2 and the others are off
-  // Brightness values 205 - 409 light up LEDs 0-3 and the others are off
-  // Brightness values 0 - 204 light up LEDs 0-4
-
-  int led0Brightness = 0;
-  int led1Brightness = 0;
-  int led2Brightness = 0;
-  int led3Brightness = 0;
-  int led4Brightness = 0;
-
-  if (brightness >= 820 && brightness <= 1023) {
-    led0Brightness = (int)((float)brightness * 1.25);
-  } else if (brightness >= 615 && brightness <= 819) {
-    led0Brightness = 255;
-    led1Brightness = (int)((float)(brightness - 205) * 1.25);
-  } else if (brightness >= 410 && brightness <= 614) {
-    led0Brightness = led1Brightness = 255;
-    led2Brightness = (int)((float)(brightness - 410) * 1.25);
-  } else if (brightness >= 205 && brightness <= 409) {
-    led0Brightness = led1Brightness = led2Brightness = 255;
-    led3Brightness = (int)((float)(brightness - 615) * 1.25);
-  } else if (brightness <= 204) {
-    led0Brightness = led1Brightness = led2Brightness = led3Brightness = 255;
-    led4Brightness = (int)((float)(brightness - 820) * 1.25);
+  // This will take the 'floor' value of the brightness divided by the photoresistor step so that
+  // we know how many LEDs to just drive at full brightness. The reminder is used to determine
+  // the duty cycle of the last LED to drive.
+  int numberOfLedsToFullBrightness = brightness / PHOTORESISTOR_STEP;
+  int remainderOfPhotoresistorBrightnessForLastLED = brightness % PHOTORESISTOR_STEP;
+  int lastLEDPWMValue = (int)((float)remainderOfPhotoresistorBrightnessForLastLED * PHOTORESISTOR_TO_LED_MULTIPLIER);
+
+  if (photoresistorAnalogValue < PHOTORESISTOR_MIN_VALUE || photoresistorAnalogValue > PHOTORESISTOR_MAX_VALUE) {
+      Serial.print("Photoresistor value is out of expected range: "); Serial.println(photoresistorAnalogValue);
+      return;
   }
-

-  Serial.println(led0Brightness);
-  Serial.println(led1Brightness);
-  Serial.println(led2Brightness);
-  Serial.println(led3Brightness);
-  Serial.println(led4Brightness);
-
-  analogWrite(LED_ARRAY_ELEMENT_0, led0Brightness);
-  analogWrite(LED_ARRAY_ELEMENT_1, led1Brightness);
-  analogWrite(LED_ARRAY_ELEMENT_2, led2Brightness);
-  analogWrite(LED_ARRAY_ELEMENT_3, led3Brightness);
-  analogWrite(LED_ARRAY_ELEMENT_4, led4Brightness);
+  Serial.println(" ------------------------------------------------------------------- ");
+  Serial.print("Number of LEDs to Drive at 100% duty cycle: "); Serial.println(numberOfLedsToFullBrightness);
+  Serial.print("Remainder of last LED brightness: "); Serial.println(remainderOfPhotoresistorBrightnessForLastLED);
+  Serial.print("PWM value of the last LED in the array that is lit: "); Serial.println(lastLEDPWMValue);
+  Serial.print("Photoresitor analog reading: "); Serial.println(photoresistorAnalogValue);
+  Serial.print("Photoresitor brightness value: "); Serial.println(brightness);
+
+  int ledCounter = 0;
+
+  // Any LEDs that need to be driven at 100% duty cycle, do that now
+  for(ledCounter = 0; ledCounter < numberOfLedsToFullBrightness; ledCounter++) {
+      //Serial.print("LED "); Serial.print(ledCounter); Serial.println(" set to full brightness");
+      analogWrite(ledArray[ledCounter], LED_MAX_BRIGHTNESS);
+  }
+
+  if (ledCounter < NUM_OF_LEDS_IN_ARRAY) {
+      // Now set the duty cycle for the only LED that will be dynamic
+      //Serial.print("LED "); Serial.print(ledCounter); Serial.print(" is PWM value: "); + Serial.println(lastLEDPWMValue);
+      analogWrite(ledArray[ledCounter], lastLEDPWMValue);
+
+      // Turn off the remaining LEDs
+      for (ledCounter++; ledCounter < NUM_OF_LEDS_IN_ARRAY; ledCounter++) {
+          //Serial.print("LED "); Serial.print(ledCounter); Serial.println(" set to off");
+          analogWrite(ledArray[ledCounter], LED_MIN_BRIGHTNESS);
+      }
+  }
 }


Only use 5 banks

Only use 5 banks

--- ableton-midi-foot-controller.ino
+++ ableton-midi-foot-controller.ino
@@ -64,6 +64,8 @@
 boolean bankUpLastState = false;

 byte bank = 0;
+
+const byte numberOfBanks = 5;

 // Modes
 const byte normalMode = 0;
@@ -353,12 +355,16 @@
   if (bankDownButton.isJustReleased()) {
     bank--;
     update = true;
+    if (bank == 255) {
+      bank = numberOfBanks - 1 ;
+    }
   } else if (bankUpButton.isJustReleased()) {
     bank++;
+    bank = bank % numberOfBanks;
     update = true;
   }
   if (update) {
-    Serial.print("Bank ");
+    Serial.print(F("Bank "));
     Serial.println(bank);
   }
 }


Suppression de la réduction de vitesse d’horloge, semble affecter la vitesse de la connexion série, (CLKPR)

--- teleInfo.ino
+++ teleInfo.ino
@@ -14,7 +14,7 @@
 #define BUFSIZE 15

 // durée entre 2 rafraichissements des données
-#define SLEEP_TIME (10 * 1000)
+#define SLEEP_TIME (60 * 1000)

 // battery voltage calculator
 // mmm la téléinfo emet un signal carré entre -25v et 25v a 1200bps, une diode, une capa, le regul du duino et hop non ?
@@ -114,9 +114,9 @@
 SoftwareSerial tiSerial( TI_RX, TI_RX );

 void setup() {
-	// reduce clock speed (reduce power consumption)
-	CLKPR = (1<<CLKPCE);
-	CLKPR = B00000011; // should put the clock at 1Mhz
+	// // reduce clock speed (reduce power consumption)
+	// CLKPR = (1<<CLKPCE);
+	// CLKPR = B00000011; // should put the clock at 1Mhz

 #ifdef DEBUG_ENABLED
 	Serial.begin( 115200 );
@@ -209,7 +209,7 @@
 	//     EJP. : option EJP
 	//     BBRx : option tempo, x est un char qui indique kkchose (relooooooou les mecs)
 	uint8_t ISOUSC; // : Intensité souscrite 2chars en Ampères - m'en fous
- 	uint32_t BASE; // Index si option = base (en Wh)
+	//uint32_t BASE; // Index si option = base (en Wh) - le probleme est qu'il semble qu'on recoive un *10000

 	uint32_t HC_HC; // Index heures creuses si option = heures creuses (en Wh)
 	uint32_t HC_HP; // Index heures pleines si option = heures creuses (en Wh)
@@ -271,7 +271,7 @@
 	if ( strcmp( label, searchLabel ) != 0 )
 		return false;

-	tmp = atol( value );
+	tmp = atoi( value );
 	if ( last == tmp )
 		return true;

@@ -376,7 +376,7 @@
 	uint8_t i; // un compteur
 	uint8_t myCS = 32, cs; // le checksum

-	// commencer par detecter le label (search for 0x20)
+	// commencer par detecter le label (search for ' ')
 	i = 0;
 	char label[ BUFSIZE ]; // etiquette
 	memset( label, 0, BUFSIZE );
@@ -391,7 +391,7 @@
 			break;
 	}

-	// la value (search for 0x20)
+	// la value (search for ' ')
 	i = 0;
 	char value[ BUFSIZE ];  // la value la plus longue ligne est ADCO / 15
 	memset( value, 0, BUFSIZE );
@@ -441,7 +441,7 @@
 	if ( strTI( label, "ADCO", value, last.ADCO, msgADCO ) )			goto readLine;
 	if ( strTI( label, "OPTARIF", value, last.OPTARIF, msgOPTARIF ) )	goto readLine;
 	if ( atoiTI( label, "ISOUSC", value, last.ISOUSC, msgISOUSC ) )		goto readLine;
-	if ( atolTI( label, "BASE", value, last.BASE, msgBASE ) )			goto readLine;
+	//if ( atolTI( label, "BASE", value, last.BASE, msgBASE ) )			goto readLine;

 	if ( atolTI( label, "HCHC", value, last.HC_HC, msgHC_HC ) )			goto readLine;
 	if ( atolTI( label, "HCHP", value, last.HC_HP, msgHC_HP ) )			goto readLine;
@@ -466,8 +466,7 @@
 	if ( atoiTI( label, "IMAX", value, last.IMAX, msgIMAX ) )			goto readLine;
 	if ( atolTI( label, "PAPP", value, last.PAPP, msgPAPP ) )			goto readLine;

-	if ( charTI( label, "HHPHC", value[0], last.HHPHC, msgHHPHC ) )
-		goto readLine;
+	if ( charTI( label, "HHPHC", value[0], last.HHPHC, msgHHPHC ) )		goto readLine;

 #ifdef DEBUG_ENABLED
 	Serial.print( F( "unkown LABEL=" ) );


system variables added

system variables added

status: system is working
issue: MA3 encoder needs mapping to EPOS2

--- send/send.ino
+++ send/send.ino
@@ -76,6 +76,13 @@
 unsigned char get_actual_velocity[8] = {0x40, 0x6C, 0x60, 0, 0, 0, 0, 0};
 unsigned char get_actual_current[8] = {0x40, 0x78, 0x60, 0, 0, 0, 0, 0};

+// *****************
+// System Variables
+// *****************
+
+int enconder_resolution = 2000; //2000 counts per turn
+int reduction = 100; // harmonic drive reduction
+
 void setup()
 {
   Serial.begin(115200);
@@ -146,6 +153,9 @@
     encoder_data = buf[4];
     encoder_data <<= 8;
     encoder_data = encoder_data | buf[5];
+
+    // 200000 qc is one
+    encoder_data

     setpoint_position[4] = buf[5]; // swaps data because for CAN, the Least Significant Bit comes first
     setpoint_position[5] = buf[4]; // swaps data because for CAN, the Least Significant Bit comes first


doc update

doc update

--- examples/Expander32/EchoInput/EchoInput.ino
+++ examples/Expander32/EchoInput/EchoInput.ino
@@ -15,8 +15,8 @@
 const uint8_t chipSelect = 10;

 // Create an object for each chip
-// Bank1 uses address 0: Pins A0,A1,A2 grounded.
-// Bank2 uses address 1: Pin A0=+5V, A1,A2 grounded.
+// Bank1 uses address 0: Pins A0,A1,A2 ground.
+// Bank2 uses address 1: Pin A0=VCC, A1,A2 ground.
 // Increase the addresses by 2 for each BA value.
 MCP23S17 Bank1(&SPI, chipSelect, 0);
 MCP23S17 Bank2(&SPI, chipSelect, 1);


Delete comunicacaoNano.ino

Delete comunicacaoNano.ino

--- MarceloForesto/RobotArchitecture/comunicacaoNano.ino
+++ MarceloForesto/RobotArchitecture/comunicacaoNano.ino
@@ -1,109 +0,0 @@
-/*
-  Software serial multple serial test
- Receives from the hardware serial, sends to software serial.
- Receives from software serial, sends to hardware serial.
- The circuit:
- * RX is digital pin 10 (connect to TX of other device)
- * TX is digital pin 11 (connect to RX of other device)
- Note:
- Not all pins on the Mega and Mega 2560 support change interrupts,
- so only the following can be used for RX:
- 10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69
- Not all pins on the Leonardo and Micro support change interrupts,
- so only the following can be used for RX:
- 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).
- created back in the mists of time
- modified 25 May 2012
- by Tom Igoe
- based on Mikal Hart's example
- This example code is in the public domain.
- ls --color=never
- */
-#include <SoftwareSerial.h>
-#include <SPI.h>
-#include <MFRC522.h>
-
-#define SS_PIN 10
-#define RST_PIN 9
-
-MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class
-
-MFRC522::MIFARE_Key key;
-
-SoftwareSerial mySerial(7, 8); // RX, TX
-
-byte  serIn;
-int code[] = {32,154,149,117}; //This is the stored UID (Unlock Card)
-int codeRead = 0;
-String rfidCode;
-char charBuf[50];
-
-void setup() {
-  pinMode(13,OUTPUT);
-  // Open serial communications and wait for port to open:
-  Serial.begin(115200);
-  SPI.begin(); // Init SPI bus
-  rfid.PCD_Init(); // Init MFRC522
-  while (!Serial) {
-    ; // wait for serial port to connect. Needed for native USB port only
-  }
-
-  // set the data rate for the SoftwareSerial port
-  mySerial.begin(115200);
-
-}
-
-void loop() { // run over and over
-  if(mySerial.available()>0){
-          serIn = mySerial.read();
-          Serial.println(char(serIn));
-          if (char(serIn) == '1'){
-            digitalWrite(13,HIGH);
-            mySerial.write("Ligou");
-          }
-          if (char(serIn) == '0'){
-            digitalWrite(13,LOW);
-            mySerial.write("Desligou");
-          }
-          if (char(serIn) == '2'){
-            while (!rfid.PICC_IsNewCardPresent());
-            delay(100);
-            readRFID();
-            delay(1000);
-            serIn = 9;
-          }
-
-  }
-}
-
-
-void readRFID()
-{
-
-  rfid.PICC_ReadCardSerial();
-  MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
-
-
-
-
-    printDec(rfid.uid.uidByte, rfid.uid.size);  //imprime o RFID
-
-
-    // Halt PICC
-  rfid.PICC_HaltA();
-
-  // Stop encryption on PCD
-  rfid.PCD_StopCrypto1();
-}
-
-void printDec(byte *buffer, byte bufferSize) {
-  for (byte i = 0; i < bufferSize; i++) {
-    rfidCode = rfidCode + buffer[i];
-  }
-  rfidCode.toCharArray(charBuf, 50);
-  mySerial.write(charBuf);
-
-  rfidCode = "";
-  memset(buffer, '\0', sizeof(buffer));
-  memset(charBuf, '\0', sizeof(charBuf));
-}


Small changes:

Small changes:

--- main_sketch/main_sketch.ino
+++ main_sketch/main_sketch.ino
@@ -6,6 +6,19 @@
 evironment.

 Fun fact, you can't name your sketch main or else the compiler freaks out
+
+Pin key;
+2- Wheels
+3- Wheels
+4- Wheels
+5- Wheels
+6- Wheels
+7- Wheels
+9 - Servo
+A2- pr
+A3- pr
+A5- IR
+

 Servo setup:   brown-  gnd
                red  -  5v
@@ -62,10 +75,19 @@
 int wheelSpeed = 0;    //speed of actual robots, dependent on wheel (0-255)

 //PHOTORES
-const int prLPin = 10;  //pin to hook up left photoresistor to
-const int prRPin = 11;  //pin to hook up right photoresistor to
+#define prLPin A3        //Analog pin for right photoresisotr
+#define prRPin A2        //Analog pin for left photoresistor
 const int black = 100; //to be experimentally determined what is black
 const int green = 60;  //same^
+const int ledPin = 12;  //pin for the led
+
+//MISC
+enum state {
+  FIND_WALL,
+  HUG_WALL,
+  ROCK,
+
+};

 void setup()
@@ -99,7 +121,7 @@

   //measure distance from sharpIR
   dis = sharp.distance();
-  //Serial.println(dis);
+  Serial.println(dis);

   //do wheel things
   handleWheels();
@@ -133,6 +155,9 @@
   //get values from both.
   int prL = analogRead(prLPin);
   int prR = analogRead(prRPin);
+//  Serial.print(prL);
+//  Serial.print(":");
+//  Serial.println(prR);

   //determine if we hit a line and what angle
   if(prL > black && prR > black) {


Corrected comments

Corrected comments

--- autorium.ino
+++ autorium.ino
@@ -17,14 +17,21 @@

 void loop() {

-  // Test Code for relay
+  test_8_board_relay();
+
+
+}
+
+// Test Code for 8 port relay
+void test_8_board_relay(){

   for(int iCounter=31;iCounter < 39;iCounter++){

-    digitalWrite(iCounter, HIGH);   // turn the LED on (HIGH is the voltage level)
-    delay(500);              // wait for a second
-    digitalWrite(iCounter, LOW);    // turn the LED off by making the voltage LOW
-    delay(400);             // wait for a second
+    digitalWrite(iCounter, HIGH);   // turn the Relay on (HIGH is the voltage level)
+    delay(500);              // wait for 500 milliseconds
+    digitalWrite(iCounter, LOW);    // turn the relay off by making the voltage LOW
+    delay(400);             // wait for 400 millisecond
   }
+
+}

-}


Deleted excess code.

Deleted excess code.

--- clients/examples/arduino/hello_lightbulb/hello_lightbulb.ino
+++ clients/examples/arduino/hello_lightbulb/hello_lightbulb.ino
@@ -26,7 +26,6 @@
 long debounceDelay = 50;

 char *jsonOff = "{\"path\":\"/api/v1/actor/perform/device/lighting\",\"requestID\":\"2\",\"perform\":\"off\",\"parameter\":\"\"}";
-//char *jsonOn = "{\"path\":\"/api/v1/actor/perform/device/lighting\",\"requestID\":\"1\",\"perform\":\"on\",\"parameter\":\"{\\\"brightness\\\":100,\\\"color\\\":{\\\"model\\\":\\\"rgb\\\",\\\"rgb\\\":{\\\"r\\\":255,\\\"g\\\":255,\\\"b\\\":255}}}\"}";
 char *jsonOn = "{\"path\":\"/api/v1/actor/perform/device/lighting\",\"requestID\":\"1\",\"perform\":\"on\",\"parameter\":\"{\\\"brightness\\\":100}\"}";
 byte mac[] = { 0x0, 0xA2, 0xDA, 0x0D, 0x90, 0xE2 };


securityBlink()

securityBlink()

this functions tells you through the leds if you can hold the hotend
depending on the temperature

--- Code/Code.ino
+++ Code/Code.ino
@@ -21,6 +21,7 @@
 #include "PID_v1.h"
 //--------------------CONSTANTS-----------------------------------------
 #define MAXTEMPERATURE 250
+#define SECURITYTEMPERATURE 50
 #define UPDATEINTERVAL 500 //compute everything every half second

 const char* tempSensors[]= {"THERM0","THERM1","THERM2","THERM3","THERM4","THERM5"};
@@ -152,16 +153,20 @@
 						//Do nothing
 					break;
 				}
-			}
-			hotends[i].update(output);
-			if (hotends[i].state == 1)					//Heating done. Temperature Reached
-			{
-				manageLEDs(hotends[i].hotendState, i);
-			} else if (hotends[i].state == 0) {			//Temperature not reached. Blinking...
-				if (hotends[i].gap < 2.0 || hotends[i].tempCelsius < MAXTEMPERATURE && connectedHotends[i] == 1)
-				{
-					blinkLeds(i);
-				}
+				hotends[i].update(output);
+			} //End if connected hotends
+				if (hotends[i].state == 1)	//Heating done. Temperature Reached
+				{
+					manageLEDs(hotends[i].hotendState, i);
+					if (hotends[i].tempCelsius <= SECURITYTEMPERATURE && connectedHotends[i] == 1)
+					{
+						securityBlink(i);
+					}
+				} else {					//Temperature not reached. Blinking...
+					if (connectedHotends[i] == 1)
+					{
+						blinkLeds(i);
+					}
 			}
 		} //for end
 		printTemperatures();
@@ -323,6 +328,24 @@
 			updateSR();
 		}
 }
+void securityBlink(int i) {
+	//This functions blinks the hotend LEDs to know that it is cold enough to hold it
+	if (i < 4){
+		bitSet(leds1,i*2);
+		updateSR();
+		} else {
+		bitSet(leds2,i*2-4);
+		updateSR();
+	}
+	delay(100);
+	if (i < 4){
+		bitClear(leds1,i*2);
+		updateSR();
+		} else {
+		bitClear(leds2,i*2 -4);
+		updateSR();
+	}
+}
 void setPIDtunings(double Kp, double Ki, double Kd) {
 	kp = Kp;
 	ki = Ki;


implementado limite mínimo e máximo para sistema de ciclo dinâmico

--- EMP-B-Due.ino
+++ EMP-B-Due.ino
@@ -73,10 +73,13 @@
     bool fotocelula_liberada = FALSO;
     bool fotocelula_cortou = FALSO;
     bool ciclo_resetado = FALSO;
+    bool reset_falso = FALSO;
     unsigned long conta_ciclo = 0;
   // Tempos do Ciclo
     // Ciclo
     unsigned long ciclo_padrao = 1500;
+    unsigned long ciclo_minimo = 900;
+    unsigned long ciclo_maximo = 2200;
     // Mandibula
     unsigned long inicio_mandibula = 550;
     unsigned long fim_mandibula = 1500;
@@ -139,7 +142,7 @@
   geraPWM(pot_solda_horizontal, &tempo_PWM_horizontal, solda_horizontal, NomeSoldaHorizontal);
   geraPWM(pot_solda_datador, &tempo_PWM_datador, solda_datador, NomeSoldaDatador);

-  if (!alarme_ativo){
+  if (!alarme_ativo) {
     standBy();
     modoTeste();
   }
@@ -147,12 +150,12 @@

 // MODOS DE TRABALHO

-void standBy(){
-  if (stand_by && !alarme_ativo){
+void standBy() {
+  if (stand_by && !alarme_ativo) {
     acionaGeral(); // Monitora botão Geral
     acionaDosador(); // Monitora botão Dosador
     acionaDatador(); // Monitora botão Datador
-    if (maquina_ligada){
+    if (maquina_ligada) {
       iniciaTrabalho();
     } else {
       reiniciaSaidas();
@@ -165,21 +168,24 @@
   }
 }

-void iniciaTrabalho(){
-  if (conta_ciclo >= 3){
+void iniciaTrabalho() {
+  if (conta_ciclo == 0) {
+    reiniciaCiclo();
+    conta_ciclo++;
+  } else if (conta_ciclo >= 3) {
     ligaFuncao(led_teste_1, "Led Teste 1"); // Exemplo para teste.
     // ciclo de trabalho
   }
   funcaoReset();
 }

-void modoAlarme(){
-  if (!alarme_ativo){
-    if (ativo(sensor_porta)){
+void modoAlarme() {
+  if (!alarme_ativo) {
+    if (ativo(sensor_porta)) {
       bloqueioPorAlarme("Sensor da Porta");
-    } else if (ativo(sensor_painel)){
+    } else if (ativo(sensor_painel)) {
       bloqueioPorAlarme("Sensor do Painel");
-    } else if (ativo(sensor_maquina)){
+    } else if (ativo(sensor_maquina)) {
       bloqueioPorAlarme("Sensor da Máquina");
     }
   }
@@ -187,7 +193,7 @@

 // FUNÇÕES ADICIONAIS

-void bloqueioPorAlarme(String texto){
+void bloqueioPorAlarme(String texto) {
   alarme_ativo = VERDADEIRO;
   stand_by = FALSO;
   escreveSerial("\n<< Alarme! >>\n");
@@ -195,45 +201,61 @@
   escreveSerial(texto + " detectou uma falha!");
 }

-void acionaGeral(){
+void acionaGeral() {
   btUmClique(bt_geral, &estbt_geral, &estbta_geral, &atr_geral, &maquina_ligada);
 }

-void acionaDosador(){
+void acionaDosador() {
   btUmClique(bt_dosador, &estbt_dosador, &estbta_dosador, &atr_dosador, &dosador_ligado);
 }

-void acionaDatador(){
-  if (maquina_ligada && !alarme_ativo){
+void acionaDatador() {
+  if (maquina_ligada && !alarme_ativo) {
     btUmClique(bt_datador, &estbt_datador, &estbta_datador, &atr_datador, &datador_ligado);
   }
 }

 void funcaoReset() {
   unsigned long tempo_atual = millis();
-  if (!ciclo_resetado && (ativo(sensor_reset) || (tempo_atual >= inicio_ciclo + ciclo_padrao))) {
-    ciclo_resetado = true;
-    conta_ciclo++;
-    escreveSerial((String) conta_ciclo + ": " + (String) (tempo_atual - inicio_ciclo));
-    reiniciaCiclo();
-  } else if (ciclo_resetado && ((tempo_atual - inicio_ciclo) > atraso_resets)) {
-    ciclo_resetado = false;
-  }
-}
-
-void reiniciaCiclo(){
+  if (!ciclo_resetado) {
+    unsigned long fim_ciclo = inicio_ciclo + ciclo_padrao;
+    unsigned long novo_ciclo = tempo_atual - inicio_ciclo;
+    if ((ativo(sensor_reset) || (tempo_atual >= fim_ciclo))) {
+      if (novo_ciclo > ciclo_minimo && novo_ciclo < ciclo_maximo) {
+        ciclo_resetado = VERDADEIRO;
+        conta_ciclo++;
+        escreveSerial((String) conta_ciclo + ": " + (String) (tempo_atual - inicio_ciclo));
+        reiniciaCiclo();
+      } else if (novo_ciclo >= ciclo_maximo) {
+        escreveSerial("Erro, reset maior que o maximo: " + (String) novo_ciclo);
+        reset_falso = VERDADEIRO;
+      } else if (novo_ciclo <= ciclo_minimo) {
+        escreveSerial("Erro, reset menor que o minimo: " + (String) novo_ciclo);
+        reset_falso = VERDADEIRO;
+      }
+    }
+  } else if ((tempo_atual - inicio_ciclo) > atraso_resets) {
+    if (ciclo_resetado) {
+      ciclo_resetado = FALSO;
+      } else if (reset_falso) {
+        reset_falso = FALSO;
+      }
+  }
+}
+
+void reiniciaCiclo() {
   inicio_ciclo = millis();
   fotocelula_liberada = FALSO;
   fotocelula_cortou = FALSO;
 }

-void geraPWM(byte pot, unsigned long *inicio, byte saida, String nome){
+void geraPWM(byte pot, unsigned long *inicio, byte saida, String nome) {
   unsigned long ativo = map(analogRead(pot), 0, 1023, 0, ciclo_PWM);
   unsigned long inativo = ciclo_PWM - ativo;
-  if (maquina_ligada && !alarme_ativo){
-    if (millis() > *inicio && millis() <= (*inicio + ativo)){
+  if (maquina_ligada && !alarme_ativo) {
+    if (millis() > *inicio && millis() <= (*inicio + ativo)) {
       liga(saida);
-    } else if (millis() > (*inicio + ativo) && millis() < (*inicio + ciclo_PWM)){
+    } else if (millis() > (*inicio + ativo) && millis() < (*inicio + ciclo_PWM)) {
       desliga(saida);
     } else if (millis() >= (*inicio + ciclo_PWM)) {
       *inicio = millis();
@@ -246,65 +268,65 @@

 // FERRAMENTAS AUXILIARES

-byte leEntrada(byte pino){
+byte leEntrada(byte pino) {
   return digitalRead(pino);
 }

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

-void ligaFuncao(byte saida, String texto){
-  if (desligado(saida)){
+void ligaFuncao(byte saida, String texto) {
+  if (desligado(saida)) {
     liga(saida);
     escreveSerial(texto + " Ligado.");
   }
 }

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

-void desligaFuncao(byte saida, String texto){
-  if (ligado(saida)){
+void desligaFuncao(byte saida, String texto) {
+  if (ligado(saida)) {
     desliga(saida);
     escreveSerial(texto + " Desligado.");
   }
 }

-boolean ligado(byte saida){
-  if (digitalRead(saida) == LIGA){
+boolean ligado(byte saida) {
+  if (digitalRead(saida) == LIGA) {
     return VERDADEIRO;
   } else {
     return FALSO;
   }
 }

-boolean desligado(byte saida){
-  if (digitalRead(saida) == DESLIGA){
+boolean desligado(byte saida) {
+  if (digitalRead(saida) == DESLIGA) {
     return VERDADEIRO;
   } else {
     return FALSO;
   }
 }

-boolean ativo(byte entrada){
-  if (digitalRead(entrada) == ALTO){
+boolean ativo(byte entrada) {
+  if (digitalRead(entrada) == ALTO) {
     return VERDADEIRO;
   } else {
     return FALSO;
   }
 }

-boolean inativo(byte entrada){
-  if (digitalRead(entrada) == BAIXO){
+boolean inativo(byte entrada) {
+  if (digitalRead(entrada) == BAIXO) {
     return VERDADEIRO;
   } else {
     return FALSO;
   }
 }

-void btUmClique(byte botao, int *estado, int *est_ant, unsigned long *atr_ant, boolean *funcao){
+void btUmClique(byte botao, int *estado, int *est_ant, unsigned long *atr_ant, boolean *funcao) {
   byte estado_atual = leEntrada(botao);
   if (estado_atual != *est_ant) {
     *atr_ant = millis();
@@ -321,13 +343,13 @@
   *est_ant = estado_atual;
 }

-void escreveSerial(String texto){
-  if (Serial){
+void escreveSerial(String texto) {
+  if (Serial) {
     Serial.println(texto);
   }
 }

-void reiniciaSaidas(){
+void reiniciaSaidas() {
   dosador_ligado = FALSO;
   datador_ligado = FALSO;
   conta_ciclo = 0;
@@ -341,7 +363,7 @@
   desliga(led_teste_3); // Para testes
 }

-void resetCompleto(){
+void resetCompleto() {
   desliga(geral);
   desliga(dosador);
   desliga(datador);
@@ -356,18 +378,18 @@
 }

-void modoTeste(){
-  if (maquina_ligada){
+void modoTeste() {
+  if (maquina_ligada) {
     ligaFuncao(geral, NomeGeral);
   } else {
     desligaFuncao(geral, NomeGeral);
   }
-  if (dosador_ligado){
+  if (dosador_ligado) {
     ligaFuncao(dosador, NomeDosador);
   } else {
     desligaFuncao(dosador, NomeDosador);
   }
-  if (datador_ligado){
+  if (datador_ligado) {
     ligaFuncao(datador, NomeDatador);
   } else {
     desligaFuncao(datador, NomeDatador);