update: arduino source code

update: arduino source code

--- arduino/openni_tracker_vulcanuino/openni_tracker_vulcanuino.ino
+++ arduino/openni_tracker_vulcanuino/openni_tracker_vulcanuino.ino
@@ -12,73 +12,118 @@
  * http://www.arduino.cc/en/Reference/Servo
  */

+// incluir librerias
 #if defined(ARDUINO) && ARDUINO >= 100
   #include "Arduino.h"
 #else
   #include <WProgram.h>
 #endif

+
+#include <Servo.h>
 #include <AccelStepper.h>
 #include <ros.h>
 #include <geometry_msgs/Point32.h>
-
+//inicializar nodo ROS
 ros::NodeHandle  nh;

+//Inicializar constantes globales
+const unsigned long TIME_TO_IDLE = 5000;
+const unsigned int STEPS_TO_360 = 3454;
+
+//Inicializar variables globales
 unsigned long lastDetection = millis();
-const unsigned long TIME_TO_IDLE = 5000;
+unsigned int XAxisDegrees, YAxisDegrees;

 AccelStepper XAxisStepper(1,4,5);
+Servo YAxisServo;

-
+//Funcion para inicializar los ejes X e Y
 void initAxis(){
    XAxisStepper.setAcceleration(1000);
    XAxisStepper.setMaxSpeed(700);
+   YAxisServo.attach(10); //attach it to pin 10
+   //pinMode(2, INPUT); // Reset position reference
 }
-void moveXAxis(int degrees){
-    if(XAxisStepper.distanceToGo() == 0){
-      XAxisStepper.moveTo(360 - (3454 / 360) * degrees);
+
+unsigned int XAxisDegrees2steps(unsigned int degrees){
+   return STEPS_TO_360 / 360 * (degrees % 360);
+}
+
+unsigned int XAxisCurrentDegrees(){
+   return XAxisDegrees2steps(XAxisStepper.currentPosition());
+}
+
+unsigned int XAxisTargetDegrees(){
+   return XAxisDegrees2steps(XAxisStepper.targetPosition());
+}
+
+
+void XAxisResetPosition(){
+    XAxisStepper.setCurrentPosition(0);
+}
+
+void XAxisSpinPositionReference(){
+  if(digitalRead(2) == 1)
+      XAxisResetPosition;
+}
+
+//Funcion para movimiento eje X
+void moveXAxis(unsigned int degrees, float speed){
+    unsigned int steps = XAxisDegrees2steps(degrees);
+    // Hasta que no le queden 0 pasos de recorrido hasta llegar al ultimo valor no sigue adelante
+    if(XAxisStepper.distanceToGo() == 0) {
+      //if(speed > 0) XAxisStepper.setSpeed(speed);
+      XAxisStepper.moveTo(steps);
   }
+}
+
+void moveXAxis(unsigned int degrees){
+    moveXAxis(degrees, 0);
+}
+
+//Funcion movimiento eje Y con Servo
+void moveYAxis(int degrees){
+    YAxisServo.write(degrees % 180);

 }

+//funcion para mover los dos ejes
 void moveTo(int degreesX, int degreesY) {
    moveXAxis(degreesX);
+   moveYAxis(degreesY);
+
 }

-
-void servo_cb( const geometry_msgs::Point32& cmd_msg){
-  lastDetection = millis();
-  moveTo(cmd_msg.x * 60, 0);
-  //servoX.write(cmd_msg.x * 180); //set servo angle, should be from 0-180
-  //servoY.write(cmd_msg.y * 180); //set servo angle, should be from 0-180
-  digitalWrite(13, HIGH-digitalRead(13));  //toggle led
+void idleState(){
+    moveYAxis(0);
+    //moveXAxis(0 : XAxisCurrentDegrees() == 0 ? 90, 0.00004);
+    moveXAxis(90);
 }

-
-ros::Subscriber<geometry_msgs::Point32> sub("vulcanuino", servo_cb);
-
-void resetPosition(){
-  //servoX.write(0);
-  //servoY.write(0);
+// Recibe el mensaje del topic al que nos suscribimos: vulcanuino
+void subscriber_cb( const geometry_msgs::Point32& cmd_msg){
+  // almacena el valor actual del tiempo en milisegundos
+  lastDetection = millis();
+  //llamar a la funcion de mover los ejes
+  moveTo(cmd_msg.x * 60, cmd_msg.y * 180);
+  //cambia el valor del led para saber que estamos recibiendo mensajes ON/OFF
+  digitalWrite(13, HIGH-digitalRead(13));
 }

 void setup(){
   pinMode(13, OUTPUT);
-
+  ros::Subscriber<geometry_msgs::Point32> sub("vulcanuino", subscriber_cb);
   initAxis();
   nh.initNode();
-  nh.subscribe(sub);
-  //servoX.attach(9); //attach it to pin 9
-  //servoY.attach(10); //attach it to pin 10
-
-
+  nh.subscribe(sub);
 }
-bool dir = false;
+
 void loop(){
   nh.spinOnce();
-  if(millis() - lastDetection > TIME_TO_IDLE)
-      moveTo(0, 0);
-
-  //moveTo(360, 0);
+  //XAxisSpinPositionReference();
+  /*if((millis() - lastDetection) > TIME_TO_IDLE)
+      idleState();*/
+  moveXAxis(180);
   XAxisStepper.run();
 }


Added non-linear intensity correct to JTagController

A 256-entry array has been added to the sketch which translates the 8-bit level to a 12-bit PWM value. This array has been gamma-corrected to approximate the non-linearity between intensity and perceived lightness of luminant sources (gamma power used: 2.2).


Update ArduCAM_Mini_2MP_Plus_short_movie_clip.ino

--- ArduCAM/examples/mini/ArduCAM_Mini_2MP_Plus_short_movie_clip/ArduCAM_Mini_2MP_Plus_short_movie_clip.ino
+++ ArduCAM/examples/mini/ArduCAM_Mini_2MP_Plus_short_movie_clip/ArduCAM_Mini_2MP_Plus_short_movie_clip.ino
@@ -134,7 +134,6 @@
 //Change to JPEG capture mode and initialize the OV5640 module
 myCAM.set_format(JPEG);
 myCAM.InitCAM();
-myCAM.set_bit(ARDUCHIP_TIM, VSYNC_LEVEL_MASK);
 #if defined (OV2640_MINI_2MP_PLUS)
   myCAM.OV2640_set_JPEG_size(OV2640_320x240);delay(1000);
 #endif


Delete setupFunctions.ino

Delete setupFunctions.ino

--- arduino/setupFunctions.ino
+++ arduino/setupFunctions.ino
@@ -1,10 +0,0 @@
-void startPins() {
-  pinMode(PAN_PIN, OUTPUT);
-  pinMode(LED_BUILTIN, OUTPUT);
-}
-
-void initialize() {
-  panServo.attach(PAN_PIN);
-  //panServo.attach(tiltPin);
-  mpuSetup();
-}


rename to keep ide happy

rename to keep ide happy

--- ardesp/waterelf_winter_garden/waterelf.ino
+++ ardesp/waterelf_winter_garden/waterelf.ino
@@ -1,935 +0,0 @@
-/////////////////////////////////////////////////////////////////////////////
-// waterelf.ino /////////////////////////////////////////////////////////////
-#include <ESP8266WiFi.h>
-#include <WiFiClient.h>
-#include <ESP8266WebServer.h>
-#include "./DNSServer.h"      // patched lib
-#include <FS.h>
-#include <OneWire.h>
-#include <DallasTemperature.h>
-#include <DHT.h>
-#include <Wire.h>
-#include <Adafruit_Sensor.h>
-#include <Adafruit_TSL2591.h>
-#include <RCSwitch.h>
-#include "Adafruit_MCP23008.h"
-
-/////////////////////////////////////////////////////////////////////////////
-// resource management stuff ////////////////////////////////////////////////
-int loopCounter = 0;
-const int LOOP_ROLLOVER = 5000; // how many loops per action slice
-const int TICK_MONITOR = 0;
-const int TICK_WIFI_DEBUG = 500;
-const int TICK_POST_DEBUG = 200;
-const int TICK_HEAP_DEBUG = 1000;
-
-/////////////////////////////////////////////////////////////////////////////
-// wifi management stuff ////////////////////////////////////////////////////
-const byte DNS_PORT = 53;
-IPAddress apIP(192, 168, 99, 1);
-IPAddress netMsk(255, 255, 255, 0);
-DNSServer dnsServer;
-ESP8266WebServer webServer(80);
-String apSSIDStr = "WaterElf-" + String(ESP.getChipId());
-const char* apSSID = apSSIDStr.c_str();
-String svrAddr = ""; // address of a local server
-
-/////////////////////////////////////////////////////////////////////////////
-// page generation stuff ////////////////////////////////////////////////////
-String pageTopStr = String(
-  "<title>WaterElf Aquaponics Helper [ID: " + apSSIDStr + "]"
-);
-const char* pageTop = pageTopStr.c_str();
-const char* pageTop2 = "</title>\n"
-  "<meta charset=\"utf-8\">"
-  "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">"
-  ""
-  "\n";
-const char* pageDefault = // TODO build the growbeds according to their num
-  "
Welcome to WaterElf
\n"
-  "
Control
\n"
-  "

\n"
-  "
Join a wifi network
\n"
-  "
Configure data sharing
\n"
-  "
"
-    "<form method='POST' action='valve1'>\n"
-    "Growbed 1: "
-    "fill <input type='radio' name='state' value='on'>\n"
-    "drain <input type='radio' name='state' value='off'>\n"
-    "<input type='submit' value='Submit'></form>\n"
-  "
"
-  "
"
-    "<form method='POST' action='valve2'>\n"
-    "Growbed 2: "
-    "fill <input type='radio' name='state' value='on'>\n"
-    "drain <input type='radio' name='state' value='off'>\n"
-    "<input type='submit' value='Submit'></form>\n"
-  "
"
-  "
"
-    "<form method='POST' action='valve3'>\n"
-    "Growbed 3: "
-    "fill <input type='radio' name='state' value='on'>\n"
-    "drain <input type='radio' name='state' value='off'>\n"
-    "<input type='submit' value='Submit'></form>\n"
-  "
"
-  "
\n"
-    "<form method='POST' action='actuate'>\n"
-    "Power: "
-    "on <input type='radio' name='state' value='on'>\n"
-    "off <input type='radio' name='state' value='off'>\n"
-    "<input type='submit' value='Submit'></form>\n"
-  "
"
-  "

\n"
-  "
Monitor
\n"
-  "

\n"
-  "
Wifi status
\n"
-  "
Sensor data
\n"
-  "

\n";
-const char* pageFooter =
-  "\n
WaterElf   "
-  "WeGrow
";
-
-/////////////////////////////////////////////////////////////////////////////
-// data monitoring stuff ////////////////////////////////////////////////////
-const boolean SEND_DATA = true;  // turn off posting of data if required here
-const int MONITOR_POINTS = 60; // number of data points to store
-typedef struct {
-  unsigned long timestamp;
-  float waterCelsius;
-  float airCelsius;
-  float airHumid;
-  uint16_t lux;
-  float pH;
-  long waterLevel1;
-  long waterLevel2;
-  long waterLevel3;
-  // TODO add last reboot
-  // TODO add free memory?
-} monitor_t;
-monitor_t monitorData[MONITOR_POINTS];
-int monitorCursor = 0;
-int monitorSize = 0;
-const int DATA_ENTRIES = 4; // size of /data rpt; must be <= MONITOR_POINTS
-void updateSensorData(monitor_t *monitorData);
-void postSensorData(monitor_t *monitorData);
-void printMonitorEntry(monitor_t m, String* buf);
-void formatMonitorEntry(monitor_t *m, String* buf, bool JSON);
-
-/////////////////////////////////////////////////////////////////////////////
-// temperature sensor stuff /////////////////////////////////////////////////
-OneWire ds(2); // DS1820 on pin 2 (a 4.7K resistor is necessary)
-DallasTemperature tempSensor(&ds);  // pass through reference to library
-void getTemperature(float* waterCelsius);
-boolean GOT_TEMP_SENSOR = false; // we'll change later if we detect sensor
-DeviceAddress tempAddr; // array to hold device address
-
-/////////////////////////////////////////////////////////////////////////////
-// humidity sensor stuff ////////////////////////////////////////////////////
-DHT dht(0, DHT22); // what digital pin we're on, plus type DHT22 aka AM2302
-boolean GOT_HUMID_SENSOR = false;  // we'll change later if we detect sensor
-
-/////////////////////////////////////////////////////////////////////////////
-// light sensor stuff ///////////////////////////////////////////////////////
-Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591); // sensor id
-boolean GOT_LIGHT_SENSOR = false; // we'll change later if we detect sensor
-
-/////////////////////////////////////////////////////////////////////////////
-// pH sensor stuff //////////////////////////////////////////////////////////
-const byte pH_Add = 0x4D;  // change this to match ph ADC address
-int pH7Cal = 2048; // assume ideal probe and amp conditions 1/2 of 4096
-int pH4Cal = 1286; // ideal probe slope -> this many 12bit units on 4 scale
-float pHStep = 59.16; // ideal probe slope
-const float vRef = 4.096; // our vRef into the ADC wont be exact
-// since you can run VCC lower than Vref its best to measure and adjust here
-const float opampGain = 5.25; //what is our Op-Amps gain (stage 1)
-boolean GOT_PH_SENSOR = false; // we'll change later if we detect sensor
-
-/////////////////////////////////////////////////////////////////////////////
-// RC switch stuff //////////////////////////////////////////////////////////
-RCSwitch mySwitch = RCSwitch();
-const int RCSW_CHANNEL = 2; // which 433 channel to use (I-IV)
-const int RCSW_HEATER = 2;  // which 433 device to switch (1-4)
-
-/////////////////////////////////////////////////////////////////////////////
-// MCP23008 stuff ///////////////////////////////////////////////////////////
-Adafruit_MCP23008 mcp; // create object for MCP23008
-const int mcpPins[] = { 0, 1, 2, 3, 6, 7, }; // pins to init in setup
-const int mcpPinsUsed = 6; // length of mcpPins array
-const int valvePinMap[][2] = {
-  { -1, -1 }, // there's no valve numbered 0...
-  { 0, 2 },   // valve 1: pump on pin 0, solenoid on pin 2
-  { 3, 6 },   // valve 2: ...
-  { 7, 1 },   // valve 3: ...
-};
-
-/////////////////////////////////////////////////////////////////////////////
-// level sensing stuff //////////////////////////////////////////////////////
-const int LEVEL_TRIG_PIN=12;
-const int LEVEL_ECHO_PIN1=13;
-const int LEVEL_ECHO_PIN2=14;
-const int LEVEL_ECHO_PIN3=16;
-boolean GOT_LEVEL_SENSOR = false;  // we'll change later if we detect sensor
-
-/////////////////////////////////////////////////////////////////////////////
-// valves and flow control //////////////////////////////////////////////////
-/*
-user settable parameters:
-- per elf:
-  - number of (controlled) beds
-  - cycle length (minutes)
-  - max simultaneous drainers (if there may be return pipe contention)
-  - min beds wet (to prevent sump overflow)
-  - max beds wet (to avoid dry pump)
-  - stagger minutes (default: cycle length / num beds)
-- per growbed:
-  - dry minutes
-  - got overflow
-  - fill level (cms below ultrasound sensor)
-
-maybe: fixed cycle time, irrespective of actual fill time, and the
-differences are absorbed into the dry time?
-*/
-class Valve { // each valve /////////////////////////////////////////////////
-  public:
-  static int counter;           // counter for setting valve number
-  int number;                   // id of this valve, counting from 1
-  char dryMins = 45;            // mins to leave bed drained per cycle
-  // in beds with overflows can be 0; else will be cycle time minus fill time
-  long startTime = -1;          // when to start cycling (after boot)
-  bool running = false;         // true when cycling started
-  bool gotOverflow = false;     // does the growbed have an overflow?
-  char fillLevel = 5;           // cms below the level sensor: drain point
-
-  Valve() { number = counter++; }
-  void stateChange(bool newState) { // turn on or off
-    Serial.print("valve ");
-    Serial.print(number);
-    int pumpMcpPin = valvePinMap[number][0];
-    int solenoidMcpPin = valvePinMap[number][1];
-
-    // trigger MOSFETs via the MCP
-    if(newState == true){
-      mcp.digitalWrite(pumpMcpPin, HIGH);
-      mcp.digitalWrite(solenoidMcpPin, HIGH);
-      Serial.println(" on");
-    } else {
-      mcp.digitalWrite(pumpMcpPin, LOW);
-      mcp.digitalWrite(solenoidMcpPin, LOW);
-      Serial.println(" off");
-    }
-  }
-  void on()  { stateChange(true); }  // fill time
-  void off() { stateChange(false); } // drain time
-  void step(monitor_t* now) {        // check conditions and adjust state
-    if(! running) {
-      if(startTime >= millis())
-        running = true;
-      else
-        return;
-    }
-  }
-};
-int Valve::counter = 1;         // definition (the above only declares)
-
-class FlowController { // the set of valves and their config ////////////////
-  public:
-  int numValves = 3;            // WARNING! call init if resetting!
-  char cycleMins = 60;          // how long is a flood/drain cycle?
-  char maxSimultDrainers = 1;   // how many beds can drain simultaneously?
-  char minBedsWet = 1;          // min beds that are full or filling
-  char maxBedsWet = 2;          // max beds that are full or filling
-  char staggerMins;             // gap to leave between valve startups
-  Valve* valves = 0;            // the valves and their states
-
-  FlowController() { init(); }
-  int getStaggerMillis() { return staggerMins * 60 * 1000; }
-  void init() {
-    Valve::counter = 1;
-    if(valves != 0) delete(valves);
-    valves = new Valve[numValves];
-
-    // set up staggered valve starts
-    staggerMins = cycleMins / numValves;
-    long t = millis();
-    long nextCycleStart = t;
-    for(int i = 0; i < numValves; i++) {
-      valves[i].startTime = nextCycleStart;
-      nextCycleStart += getStaggerMillis();
-    }
-  }
-  void step(monitor_t* now) {
-    for(int i = 0; i < numValves; i++)
-      valves[i].step(now);
-  }
-};
-FlowController flowController;
-
-/////////////////////////////////////////////////////////////////////////////
-// config utils /////////////////////////////////////////////////////////////
-boolean getCloudShare();
-void setCloudShare(boolean b);
-String getSvrAddr();
-void setSvrAddr(String s);
-
-/////////////////////////////////////////////////////////////////////////////
-// misc utils ///////////////////////////////////////////////////////////////
-void ledOn();
-void ledOff();
-String ip2str(IPAddress address);
-
-/////////////////////////////////////////////////////////////////////////////
-// setup ////////////////////////////////////////////////////////////////////
-void setup() {
-  Serial.begin(115200);
-
-  pinMode(BUILTIN_LED, OUTPUT); // turn built-in LED on
-  blink(3);                     // signal we're starting setup
-
-  // read persistent config
-  SPIFFS.begin();
-  svrAddr = getSvrAddr();
-
-  // start the sensors, the DNS and webserver, etc.
-  startPeripherals();
-  startAP();
-  printIPs();
-  startDNS();
-  startWebServer();
-
-  // initialise the MCP and the flow controller
-  flowController.init();
-  mcp.begin();                  // use default address 0 for mcp23008
-  for(int i = 0; i < mcpPinsUsed; i++)
-    mcp.pinMode(mcpPins[i], OUTPUT);
-
-  // try and set the host name
-  if(WiFi.hostname("waterelf"))
-    Serial.println("set hostname succeeded");
-  else
-    Serial.println("set hostname failed");
-  delay(300); blink(3);         // signal we've finished config
-}
-
-/////////////////////////////////////////////////////////////////////////////
-// looooooooooooooooooooop //////////////////////////////////////////////////
-void loop() {
-  dnsServer.processNextRequest();
-  webServer.handleClient();
-
-  if(loopCounter == TICK_MONITOR) { // monitor levels, step valves, push data
-    monitor_t* now = &monitorData[monitorCursor];
-    if(monitorSize < MONITOR_POINTS)
-      monitorSize++;
-    now->timestamp = millis();
-    if(GOT_TEMP_SENSOR) {
-      getTemperature(&now->waterCelsius);               yield();
-    }
-    if(GOT_HUMID_SENSOR) {
-      getHumidity(&now->airCelsius, &now->airHumid);    yield();
-    }
-    if(GOT_LIGHT_SENSOR) { getLight(&now->lux);         yield(); }
-    if(GOT_PH_SENSOR) { getPH(&now->pH);                yield(); }
-    if(GOT_LEVEL_SENSOR) {
-      getLevel(LEVEL_ECHO_PIN1, &now->waterLevel1);     yield();
-      getLevel(LEVEL_ECHO_PIN2, &now->waterLevel2);     yield();
-      getLevel(LEVEL_ECHO_PIN3, &now->waterLevel3);     yield();
-    }
-
-    flowController.step(now); yield();  // set valves on and off etc.
-    if(SEND_DATA) {                     // push data to the cloud
-      postSensorData(&monitorData[monitorCursor]); yield();
-    }
-
-    if(++monitorCursor == MONITOR_POINTS)
-      monitorCursor = 0;
-  }
-
-  if(loopCounter == TICK_WIFI_DEBUG) {
-    Serial.print("SSID: "); Serial.print(apSSID);
-    Serial.print("; IP address(es): local="); Serial.print(WiFi.localIP());
-    Serial.print("; AP="); Serial.println(WiFi.softAPIP());
-  }
-  if(loopCounter == TICK_HEAP_DEBUG) {
-    Serial.print("free heap="); Serial.println(ESP.getFreeHeap());
-  }
-
-  if(loopCounter++ == LOOP_ROLLOVER) loopCounter = 0;
-}
-
-/////////////////////////////////////////////////////////////////////////////
-// wifi and web server management stuff /////////////////////////////////////
-void startAP() {
-  WiFi.mode(WIFI_AP_STA);
-  WiFi.softAPConfig(apIP, apIP, netMsk);
-  WiFi.softAP(apSSID);
-  Serial.println("Soft AP started");
-}
-void startDNS() {
-  dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
-  dnsServer.start(DNS_PORT, "*", apIP);
-  Serial.println("DNS server started");
-}
-void printIPs() {
-  Serial.print("AP SSID: ");
-  Serial.print(apSSID);
-  Serial.print("; IP address(es): local=");
-  Serial.print(WiFi.localIP());
-  Serial.print("; AP=");
-  Serial.println(WiFi.softAPIP());
-}
-void startWebServer() {
-  webServer.on("/", handle_root);
-  webServer.on("/generate_204", handle_root); // Android support
-  webServer.on("/L0", handle_root);
-  webServer.on("/L2", handle_root);
-  webServer.on("/ALL", handle_root);
-  webServer.onNotFound(handleNotFound);
-  webServer.on("/wifi", handle_wifi);
-  webServer.on("/wifistatus", handle_wifistatus);
-  webServer.on("/serverconf", handle_serverconf);
-  webServer.on("/wfchz", handle_wfchz);
-  webServer.on("/svrchz", handle_svrchz);
-  webServer.on("/data", handle_data);
-  webServer.on("/actuate", handle_actuate);
-  webServer.on("/valve1", handle_valve1);
-  webServer.on("/valve2", handle_valve2);
-  webServer.on("/valve3", handle_valve3);
-  webServer.begin();
-  Serial.println("HTTP server started");
-}
-void handleNotFound() {
-  Serial.print("URI Not Found: ");
-  Serial.println(webServer.uri());
-  // TODO send redirect to /? or just use handle_root?
-  webServer.send(200, "text/plain", "URI Not Found");
-}
-void handle_root() {
-  Serial.println("serving page notionally at /");
-  String toSend = pageTop;
-  toSend += pageTop2;
-  toSend += pageDefault;
-  toSend += pageFooter;
-  webServer.send(200, "text/html", toSend);
-}
-void handle_data() {
-  Serial.println("serving page at /data");
-  String toSend = pageTop;
-  toSend += ": Sensor Data";
-  toSend += pageTop2;
-  toSend += "\n
Sensor Data

\n";
-
-  int mSize = monitorSize;
-  for(
-    int i = monitorCursor - 1, j = 1;
-    j <= DATA_ENTRIES && j <= monitorSize;
-    i--, j++
-  ) {
-    formatMonitorEntry(&monitorData[i], &toSend, false);
-    toSend += "\n";
-    if(i == 0)
-      i = MONITOR_POINTS;
-  }
-
-  toSend += "
\n";
-  toSend += pageFooter;
-  webServer.send(200, "text/html", toSend);
-}
-String genAPForm() {
-  String f = pageTop;
-  f += ": Wifi Config";
-  f += pageTop2;
-  f += "
Choose a wifi access point to join
\n";
-  f += "
Signal strength in brackets, lower is better

\n";
-
-  const char *checked = " checked";
-
-  int n = WiFi.scanNetworks();
-  Serial.print("scan done: ");
-  if(n == 0) {
-    Serial.println("no networks found");
-    f += "No wifi access points found :-( ";
-    f += "Back
Try again?
\n";
-  } else {
-    Serial.print(n);
-    Serial.println(" networks found");
-    f += "<form method='POST' action='wfchz'> ";
-    for(int i = 0; i < n; ++i) {
-      // print SSID and RSSI for each network found
-      Serial.print(i + 1);
-      Serial.print(": ");
-      Serial.print(WiFi.SSID(i));
-      Serial.print(" (");
-      Serial.print(WiFi.RSSI(i));
-      Serial.print(")");
-      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
-
-      f.concat("<input type='radio' name='ssid' value='");
-      f.concat(WiFi.SSID(i));
-      f.concat("'");
-      f.concat(checked);
-      f.concat(">");
-      f.concat(WiFi.SSID(i));
-      f.concat(" (");
-      f.concat(WiFi.RSSI(i));
-      f.concat(" dBm)");
-      f.concat("
\n");
-      checked = "";
-    }
-    f += "
Pass key: <input type='textarea' name='key'>

 ";
-    f += "<input type='submit' value='Submit'></form>
";
-  }
-
-  f += pageFooter;
-  return f;
-}
-void handle_wifi() {
-  Serial.println("serving page at /wifi");
-  String toSend = genAPForm();
-  webServer.send(200, "text/html", toSend);
-}
-
-void handle_wifistatus() {
-  Serial.println("serving page at /wifistatus");
-
-  String toSend = pageTop;
-  toSend += ": Wifi Status";
-  toSend += pageTop2;
-  toSend += "\n
Wifi Status

\n";
-
-  toSend += "\n
SSID: ";
-  toSend += WiFi.SSID();
-  toSend += "
";
-  toSend += "\n
Status: ";
-  switch(WiFi.status()) {
-    case WL_IDLE_STATUS:
-      toSend += "WL_IDLE_STATUS
"; break;
-    case WL_NO_SSID_AVAIL:
-      toSend += "WL_NO_SSID_AVAIL
"; break;
-    case WL_SCAN_COMPLETED:
-      toSend += "WL_SCAN_COMPLETED
"; break;
-    case WL_CONNECTED:
-      toSend += "WL_CONNECTED
"; break;
-    case WL_CONNECT_FAILED:
-      toSend += "WL_CONNECT_FAILED
"; break;
-    case WL_CONNECTION_LOST:
-      toSend += "WL_CONNECTION_LOST
"; break;
-    case WL_DISCONNECTED:
-      toSend += "WL_DISCONNECTED
"; break;
-    default:
-       toSend += "unknown
";
-  }
-
-  toSend += "\n
Local IP: ";   toSend += ip2str(WiFi.localIP());
-  toSend += "
\n";
-  toSend += "\n
Soft AP IP: "; toSend += ip2str(WiFi.softAPIP());
-  toSend += "
\n";
-  toSend += "\n
AP SSID name: "; toSend += apSSID;
-  toSend += "
\n";
-
-  toSend += "

";
-
-  toSend += pageFooter;
-  webServer.send(200, "text/html", toSend);
-}
-void handle_wfchz() {
-  Serial.println("serving page at /wfchz");
-  String toSend = pageTop;
-  toSend += ": joining wifi network";
-  toSend += pageTop2;
-  String ssid = "";
-  String key = "";
-
-  for(uint8_t i = 0; i < webServer.args(); i++ ) {
-    //Serial.println(" " + webServer.argName(i) + ": " + webServer.arg(i));
-    if(webServer.argName(i) == "ssid")
-      ssid = webServer.arg(i);
-    else if(webServer.argName(i) == "key")
-      key = webServer.arg(i);
-  }
-
-  if(ssid == "") {
-    toSend += "
Ooops, no SSID...?
";
-    toSend += "
Looks like a bug :-(
";
-  } else {
-    toSend += "
Done! Now trying to join network...
";
-    toSend += "
Check wifi status here.
";
-    char ssidchars[ssid.length()+1];
-    char keychars[key.length()+1];
-    ssid.toCharArray(ssidchars, ssid.length()+1);
-    key.toCharArray(keychars, key.length()+1);
-    WiFi.begin(ssidchars, keychars);
-  }
-
-  toSend += pageFooter;
-  webServer.send(200, "text/html", toSend);
-}
-String genServerConfForm() {
-  String f = pageTop;
-  f += ": Server Config";
-  f += pageTop2;
-  f += "
Configure data sharing

\n";
-
-  f += "<form method='POST' action='svrchz'> ";
-  f += "
Local server IP address: ";
-  f += "<input type='textarea' name='svraddr'>

 ";
-  //f += "Sharing on WeGrow.social: ";
-  // TODO set checked dependent on getCloudShare()
-  //f += "on <input type='radio' name='wegrow' value='on' checked>\n";
-  //f += "off <input type='radio' name='wegrow' value='off'>

\n";
-  f += "<input type='submit' value='Submit'></form>
";
-
-  f += pageFooter;
-  return f;
-}
-void handle_serverconf() {
-  Serial.println("serving page at /serverconf");
-  String toSend = genServerConfForm();
-  webServer.send(200, "text/html", toSend);
-}
-void handle_svrchz() {
-  Serial.println("serving page at /svrchz");
-  String toSend = pageTop;
-  toSend += ": data sharing configured";
-  toSend += pageTop2;
-
-  boolean cloudShare = false;
-  for(uint8_t i = 0; i < webServer.args(); i++) {
-    if(webServer.argName(i) == "svraddr") {
-      svrAddr = webServer.arg(i);
-      toSend += "
Added local server config...
";
-      toSend += "
...at ";
-      toSend += svrAddr;
-      toSend += "
";
-    } else if(webServer.argName(i) == "key") {
-      if(webServer.arg(i) == "on")
-        cloudShare = true;
-    }
-  }
-
-  // persist the config
-  if(svrAddr.length() > 0) setSvrAddr(svrAddr);
-  setCloudShare(cloudShare);
-
-  // TODO some way of verifying if server config worked
-  // add srvstatus, or roll that into wifistatus, or...?
-
-  toSend += pageFooter;
-  webServer.send(200, "text/html", toSend);
-}
-void handle_actuate() {
-  Serial.println("serving page at /actuate");
-  String toSend = pageTop;
-  toSend += ": Setting Actuator";
-  toSend += pageTop2;
-
-  boolean newState = false;
-  for(uint8_t i = 0; i < webServer.args(); i++ ) {
-    if(webServer.argName(i) == "state") {
-      if(webServer.arg(i) == "on")
-        newState = true;
-    }
-  }
-
-  // now we trigger the 433 transmitter
-  if(newState == true){
-    mySwitch.switchOn(RCSW_CHANNEL, RCSW_HEATER);
-    Serial.println("Actuator on");
-  } else {
-    mySwitch.switchOff(RCSW_CHANNEL, RCSW_HEATER);
-    Serial.println("Actuator off");
-  }
-
-  toSend += "
Actuator triggered
\n";
-  toSend += "
(New state should be ";
-  toSend += (newState) ? "on" : "off";
-  toSend += ".)
\n";
-  toSend += pageFooter;
-  webServer.send(200, "text/html", toSend);
-}
-void handle_valve1() { handle_valve(0); } // valves in the UI are...
-void handle_valve2() { handle_valve(1); } // ...numbered from 1, but...
-void handle_valve3() { handle_valve(2); } // ...from 0 in the FlowController
-void handle_valve(int valveNum) {
-  Serial.print("serving page at /valve");
-  Serial.println(valveNum + 1);
-  String toSend = pageTop;
-  toSend += ": Setting Water Valve ";
-  toSend += valveNum + 1;
-  toSend += pageTop2;
-
-  boolean newState = false;
-  for(uint8_t i = 0; i < webServer.args(); i++ ) {
-    if(webServer.argName(i) == "state") {
-      if(webServer.arg(i) == "on")
-        newState = true;
-    }
-  }
-  flowController.valves[valveNum].stateChange(newState);
-
-  toSend += "
Water Valve ";
-  toSend += valveNum + 1;
-  toSend += " triggered
\n";
-  toSend += "
(New state should be ";
-  toSend += (newState) ? "on" : "off";
-  toSend += ".)
\n";
-  toSend += pageFooter;
-  webServer.send(200, "text/html", toSend);
-}
-
-/////////////////////////////////////////////////////////////////////////////
-// sensor/actuator stuff ////////////////////////////////////////////////////
-void startPeripherals() {
-  Serial.println("\nstartPeripherals...");
-  mySwitch.enableTransmit(15);   // RC transmitter is connected to Pin 15
-
-  tempSensor.begin();     // start the onewire temperature sensor
-  if(tempSensor.getDeviceCount()==1) {
-    GOT_TEMP_SENSOR = true;
-    tempSensor.getAddress(tempAddr, 0);
-    tempSensor.setResolution(tempAddr, 12); // 12 bit res (DS18B20 does 9-12)
-  }
-
-  dht.begin();    // start the humidity and air temperature sensor
-  float airHumid = dht.readHumidity();
-  float airCelsius = dht.readTemperature();
-  if (isnan(airHumid) || isnan(airCelsius)) {
-    Serial.println("failed to find humidity sensor");
-  } else {
-    GOT_HUMID_SENSOR = true;
-  }
-
-  // configure the level sensors
-  pinMode(LEVEL_TRIG_PIN, OUTPUT);
-  pinMode(LEVEL_ECHO_PIN1, INPUT);
-  pinMode(LEVEL_ECHO_PIN2, INPUT);
-  pinMode(LEVEL_ECHO_PIN3, INPUT);
-  GOT_LEVEL_SENSOR = true;
-
-  Wire.begin();
-  byte error;
-  Wire.beginTransmission(0x29);
-  error = Wire.endTransmission();
-  if(error==0){
-    GOT_LIGHT_SENSOR = true;
-    tsl.begin();  // startup light sensor
-    // can change gain of light sensor on the fly, to adapt
-    // brighter/dimmer light situations
-    // tsl.setGain(TSL2591_GAIN_LOW);    // 1x gain (bright light)
-    tsl.setGain(TSL2591_GAIN_MED);       // 25x gain
-    // tsl.setGain(TSL2591_GAIN_HIGH);   // 428x gain
-
-    // changing the integration time gives you a longer time over which to
-    // sense light longer timelines are slower, but are good in very low light
-    // situtations!
-    // tsl.setTiming(TSL2591_INTEGRATIONTIME_100MS); // shortest (bright)
-    tsl.setTiming(TSL2591_INTEGRATIONTIME_200MS);
-    // tsl.setTiming(TSL2591_INTEGRATIONTIME_300MS);
-    // tsl.setTiming(TSL2591_INTEGRATIONTIME_400MS);
-    // tsl.setTiming(TSL2591_INTEGRATIONTIME_500MS);
-    // tsl.setTiming(TSL2591_INTEGRATIONTIME_600MS); // longest (dim)
-  }
-
-  //Wire.begin();
-  Wire.beginTransmission(pH_Add);
-  error = Wire.endTransmission();
-  if(error==0){
-    GOT_PH_SENSOR = true;
-    Serial.println("Found pH sensor");
-  }
-}
-void postSensorData(monitor_t *monitorData) {
-  //Serial.println("\npostSensorData");
-
-  // create a JSON form
-  String jsonBuf = "";
-  formatMonitorEntry(monitorData, &jsonBuf, true);
-  String envelope = "POST /fishydata HTTP/1.1\n";
-  envelope += "Content-Type: application/json\n";
-  envelope += "Content-Length: " ;
-  envelope += jsonBuf.length();
-  envelope += "\nConnection: close\n\n";
-  envelope += jsonBuf;
-  //Serial.println(envelope);
-
-  WiFiClient couchClient;
-  if(couchClient.connect(svrAddr.c_str(), 5984)) {
-    Serial.print(svrAddr);
-    Serial.println(" - connected as couch server");
-    couchClient.print(envelope);
-  } else {
-    Serial.print(svrAddr);
-    Serial.println(" - no couch server");
-  }
-
-  Serial.println("");
-  return;
-}
-void formatMonitorEntry(monitor_t *m, String* buf, bool JSON) {
-  if(JSON) buf->concat("{ ");
-  buf->concat("~timestamp~+ ");
-  buf->concat(m->timestamp);
-  if(GOT_TEMP_SENSOR){
-    buf->concat("^ ~waterTemp~+ ");
-    buf->concat(m->waterCelsius);
-    if(! JSON) buf->concat("\t\u00B0C");
-  }
-  if(GOT_HUMID_SENSOR){
-    buf->concat("^ ~airTemp~+ ");
-    buf->concat(m->airCelsius);
-    if(! JSON) buf->concat("\t\u00B0C");
-    buf->concat("^ ~humidity~+ ");
-    buf->concat(m->airHumid);
-    if(! JSON) buf->concat("\t%RH");
-  }
-  if(GOT_LIGHT_SENSOR){
-    buf->concat("^ ~light~+ ");
-    buf->concat(m->lux);
-    if(! JSON) buf->concat("\tlux");
-  }
-  if(GOT_PH_SENSOR){
-    buf->concat("^ ~pH~+ ");
-    if(! JSON) buf->concat("\t ");
-    buf->concat(m->pH);
-  }
-  if(GOT_LEVEL_SENSOR){
-    buf->concat("^ ~waterLevel1~+ "); buf->concat(m->waterLevel1);
-    if(! JSON) buf->concat("\tcm");
-    buf->concat("^ ~waterLevel2~+ "); buf->concat(m->waterLevel2);
-    if(! JSON) buf->concat("\tcm");
-    buf->concat("^ ~waterLevel3~+ "); buf->concat(m->waterLevel3);
-    if(! JSON) buf->concat("\tcm");
-  }
-  if(JSON) {
-    buf->concat(" }");
-    buf->replace('~', '"');
-    buf->replace('^', ',');
-    buf->replace('+', ':');
-  } else { // remove quotes and commas
-    buf->replace('~', ' ');
-    buf->replace('^', '\n');
-    buf->replace('+', '\t');
-    buf->concat("\n");
-  }
-}
-void getTemperature(float* waterCelsius) {
-  tempSensor.requestTemperatures(); // send command to get temperatures
-  (*waterCelsius) = tempSensor.getTempC(tempAddr);
-  Serial.print("Water temp: ");
-  Serial.print(*waterCelsius);
-  Serial.println(" C, ");
-  return;
-}
-void getHumidity(float* airCelsius, float* airHumid) {
-  (*airCelsius) = dht.readTemperature();
-  (*airHumid) = dht.readHumidity();
-  Serial.print("Air Temp: ");
-  Serial.print(*airCelsius);
-  Serial.print(" C, ");
-  Serial.print("Humidity: ");
-  Serial.print(*airHumid);
-  Serial.println(" %RH, ");
-  return;
-}
-void getLight(uint16_t* lux) {
-  sensors_event_t event;
-  tsl.getEvent(&event);
-  (*lux) = event.light;
-  Serial.print("Light: ");
-  Serial.print(*lux);
-  Serial.println(" Lux");
-  return;
-}
-void getPH(float* pH) {
-// this is our I2C ADC interface section
-// assign 2 BYTES variables to capture the LSB & MSB (or Hi Low in this case)
-  byte adc_high;
-  byte adc_low;
-  // we'll assemble the 2 in this variable
-  int adc_result;
-
-  Wire.requestFrom(pH_Add, 2); // requests 2 bytes
-  while(Wire.available() < 2); // while two bytes to receive
-  adc_high = Wire.read();      // set...
-  adc_low = Wire.read();       // ...them
-  // now assemble them, remembering byte maths; a Union works well here too
-  adc_result = (adc_high * 256) + adc_low;
-  // we have a our Raw pH reading from the ADC; now figure out what the pH is
-  float milliVolts = (((float)adc_result/4096)*vRef)*1000;
-  float temp = ((((vRef*(float)pH7Cal)/4096)*1000) - milliVolts) / opampGain;
-  (*pH) = 7-(temp/pHStep);
-  Serial.print("pH: ");
-  Serial.print(*pH);
-  Serial.println(" pH");
-  return;
-}
-void getLevel(int echoPin, long* waterLevel) {
-  long duration;
-  int TIMEOUT = 15000;                          // how long to wait for pulse
-
-  digitalWrite(LEVEL_TRIG_PIN, LOW);            // prepare for ping
-  delayMicroseconds(2);
-  digitalWrite(LEVEL_TRIG_PIN, HIGH);           // start ping
-  delayMicroseconds(10);                        // allow 10ms ping
-  digitalWrite(LEVEL_TRIG_PIN, LOW);            // stop ping
-  duration = pulseIn(echoPin, HIGH, TIMEOUT);   // wait for response
-
-  (*waterLevel) = (duration/2) / 29.1;
-
-  Serial.print("Water Level: ");
-  Serial.print(*waterLevel);
-  Serial.println(" cm, ");
-  return;
-}
-
-/////////////////////////////////////////////////////////////////////////////
-// config utils /////////////////////////////////////////////////////////////
-boolean getCloudShare() {
-  boolean b = false;
-  File f = SPIFFS.open("/cloudShare.txt", "r");
-  if(f) {
-    b = true;
-    f.close();
-  }
-  return b;
-}
-void setCloudShare(boolean b) {
-  if(b) {
-    File f = SPIFFS.open("/cloudShare.txt", "w");
-    f.println("");
-    f.close();
-  } else {
-    SPIFFS.remove("/cloudShare.txt");
-  }
-}
-String getSvrAddr() {
-  String s = "";
-  File f = SPIFFS.open("/svrAddr.txt", "r");
-  if(f) {
-    s = f.readString();
-    s.trim();
-    f.close();
-  }
-  return s;
-}
-void setSvrAddr(String s) {
-  File f = SPIFFS.open("/svrAddr.txt", "w");
-  f.println(s);
-  f.close();
-}
-
-/////////////////////////////////////////////////////////////////////////////
-// misc utils ///////////////////////////////////////////////////////////////
-void ledOn()  { digitalWrite(BUILTIN_LED, LOW); }
-void ledOff() { digitalWrite(BUILTIN_LED, HIGH); }
-void blink(int times) {
-  ledOff();
-  for(int i=0; i<times; i++) {
-    ledOn(); delay(300); ledOff(); delay(300);
-  }
-  ledOff();
-}
-String ip2str(IPAddress address) {
-  return
-    String(address[0]) + "." + String(address[1]) + "." +
-    String(address[2]) + "." + String(address[3]);
-}


Made alignment stars generic, removed some fluff.

--- arduino-code/Stellarduino/Stellarduino.ino
+++ arduino-code/Stellarduino/Stellarduino.ino
@@ -8,15 +8,17 @@
  * Version: 0.3 Meade Autostar
  * Author: Casey Fulton, casey AT caseyfulton DOT com
  * License: MIT, http://opensource.org/licenses/MIT
+ *
+ * Choosing new alignment stars
+ * Feel free to replace the alignment stars below with ones that are visible
+ * from your location/season.
  */
-

 #include <Encoder.h>
 #include <LiquidCrystal.h>
 #include <math.h>
 //#include <Wire.h>
 //#include "RTClib.h"
-//#include <SoftwareSerial.h>

 #define WAITING_FOR_START 1
 #define WAITING_FOR_END 2
@@ -26,8 +28,9 @@
 #define GET_DEC "GD"
 #define CHANGE_PRECISION "U"

-
-// some types
+#define DEBUG false
+
+// Structure for storing star data.
 typedef struct {
   float time;
   float ra;
@@ -35,6 +38,7 @@
   float alt;
   float az;
   String name;
+  float vmag;
 } Star;

 //RTC_DS1307 RTC;
@@ -51,11 +55,8 @@
 float initialTime;

 // alignment stars
-//Star aAnd = {5.619669, 0.034470, 0.506809, 1.732239, 1.463808, "α And"};
-//Star aUmi = {5.659376, 0.618501, 1.557218, 5.427625, 0.611563, "α Umi"};
-
-Star rigelK = {0.0, 3.837912142664153, -1.0618086768405413, 0.0, 0.0, "Rigel K"};
-Star arcturus = {0.0, 3.733528341608887, 0.33479293562700113, 0.0, 0.0, "Arcturus"};
+Star alignmentStar1 = {0.0, 3.83797175293031, -1.06177589858756,  0.0, 0.0, "Rigel K",  -0.01};
+Star alignmentStar2 = {0.0, 3.73352834160889,  0.334797783763812, 0.0, 0.0, "Arcturus", -0.04};

 // calculation vectors
 float firstTVector[3];
@@ -92,9 +93,6 @@
 // display
 LiquidCrystal lcd(6, 7, 8, 9, 10, 11);

-// OMFG Software Serial, need to ditch this in favour of USB port!
-//SoftwareSerial mySerial(13, 12); // RX, TX
-
 // encoder steps per revolution of scope (typically 4 * CPR * gearing)
 const int altSPR = 10000;
 const int azSPR = 10000;
@@ -109,7 +107,6 @@

 void setup()
 {
-  //mySerial.begin(9600);
   Serial.begin(9600);
   lcd.begin(16, 2);
   lcd.clear();
@@ -118,28 +115,30 @@
   // setup encoders
   altMultiplier = 2.0 * M_PI / ((float)altSPR);
   azMultiplier = -2.0 * M_PI / ((float)azSPR);
-
+
   doAlignment();
-
+
   calculateTransforms();
-
-/*  Serial.println("Telescope matrix:");
-  printMatrix(telescopeMatrix);
-
-  Serial.println("Celestial matrix:");
-  printMatrix(celestialMatrix);
-
-  Serial.println("Inverse Celestial matrix:");
-  printMatrix(inverseMatrix);
-
-  Serial.println("Transform matrix:");
-  printMatrix(transformMatrix);
-
-  Serial.println("Inverse Transform matrix:");
-  printMatrix(inverseTransformMatrix); */
-
-  clearScreen();
-
+
+  if (DEBUG) {
+    Serial.println("Telescope matrix:");
+    printMatrix(telescopeMatrix);
+
+    Serial.println("Celestial matrix:");
+    printMatrix(celestialMatrix);
+
+    Serial.println("Inverse Celestial matrix:");
+    printMatrix(inverseMatrix);
+
+    Serial.println("Transform matrix:");
+    printMatrix(transformMatrix);
+
+    Serial.println("Inverse Transform matrix:");
+    printMatrix(inverseTransformMatrix);
+  }
+
+  clearScreen();
+
   state = WAITING_FOR_START;
   highPrecision = true;
 }
@@ -148,38 +147,36 @@
 {
   altT = altMultiplier * altEncoder.read();
   azT = azMultiplier * azEncoder.read();
-
+
   fillVectorWithT(obsTVector, altT, azT);
   fillMatrixWithProduct(obsCVector, inverseTransformMatrix, obsTVector, 3, 3, 1);
-  fillStarWithCVector(obs, obsCVector); // OMFG THIS IS PROBABLY INCORRECT
-
-
-/*
-  Serial.println("Observed vector:");
-  printVector(obsTVector);
-  Serial.println("Transformed celestial vector:");
-  printVector(obsCVector);
-  Serial.println("Celestial coordinates:");
-  Serial.print(obs[0]);
-  Serial.print(",");
-  Serial.println(obs[1]);
-
-  while(Serial.available() == 0)
-  {
-    // do nothing
-  }
-  Serial.read();
-*/
+  fillStarWithCVector(obs, obsCVector);
+
+  if (DEBUG) {
+    Serial.println("Observed vector:");
+    printVector(obsTVector);
+    Serial.println("Transformed celestial vector:");
+    printVector(obsCVector);
+    Serial.println("Celestial coordinates:");
+    Serial.print(obs[0]);
+    Serial.print(",");
+    Serial.println(obs[1]);
+
+    // wait for input from serial before continuing
+    while(Serial.available() == 0)
+    {
+      // do nothing
+    }
+    Serial.read();
+  }

   lcd.setCursor(5,0);
-//  lcd.print(obs[0] * rad2deg, 3);
   lcd.print(rad2hm(obs[0]));
   lcd.print(" ");
   lcd.setCursor(5,1);
-//  lcd.print(obs[1] * rad2deg, 3);
   lcd.print(rad2dm(obs[1]));
   lcd.print(" ");
-
+
   // if there's a serial request waiting, process it
   if (Serial.available()) {
     processSerial();
@@ -200,7 +197,6 @@

 void fillStarWithCVector(float* star, float* v)
 {
-  // OMFG THIS IS PROBABLY INCORRECT
   star[0] = atan(v[1] / v[0]) + siderealFraction * ((float)millis() / 86400000.0f * 2.0 * M_PI - initialTime);
   if(v[0] < 0) star[0] = star[0] + M_PI;
   star[1] = asin(v[2]);
@@ -235,7 +231,7 @@
   int pivrow;
   int pivrows[9];
   int i,j,k;
-
+
   for(k = 0; k < 3; k++) {
     temp = 0;
     for(i = k; i < 3; i++) {
@@ -263,7 +259,7 @@
     for(j = 0; j < 3; j++) {
       m[k * 3 + j] = m[k * 3 + j] * temp;
     }
-
+
     for(i = 0; i < 3; i++) {
       if(i != k) {
         temp = m[i* 3 + k];
@@ -274,7 +270,7 @@
       }
     }
   }
-
+
   for(k = 2; k >= 0; k--) {
     if(pivrows[k] != k) {
       for(i = 0; i < 3; i++) {
@@ -308,72 +304,72 @@
 void doAlignment() {
   // set initial time - actual time not necessary, just the difference!
   initialTime = (float)millis() / 86400000.0f * 2.0 * M_PI;
-
+
   // ask user to point scope at first star
   lcd.print("Point: ");
-  lcd.print(rigelK.name);
+  lcd.print(alignmentStar1.name);
   lcd.setCursor(0,1);
   lcd.print("Then press OK");

   // wait for button press
   while(digitalRead(OK_BTN) == LOW);
-  rigelK.time = (float)millis() / 86400000.0f * 2.0 * M_PI;
-  rigelK.alt = altMultiplier * altEncoder.read();
-  rigelK.az = azMultiplier * azEncoder.read();
+  alignmentStar1.time = (float)millis() / 86400000.0f * 2.0 * M_PI;
+  alignmentStar1.alt = altMultiplier * altEncoder.read();
+  alignmentStar1.az = azMultiplier * azEncoder.read();

   lcd.clear();
   lcd.print("Alt set: ");
-  lcd.print(rigelK.alt * rad2deg, 3);
+  lcd.print(alignmentStar1.alt * rad2deg, 3);
   lcd.setCursor(0,1);
   lcd.print("Az set: ");
-  lcd.print(rigelK.az * rad2deg, 3);
+  lcd.print(alignmentStar1.az * rad2deg, 3);

   delay(2000);

   // ask user to point scope at second star
   lcd.clear();
   lcd.print("Point: ");
-  lcd.print(arcturus.name);
+  lcd.print(alignmentStar2.name);
   lcd.setCursor(0,1);
   lcd.print("Then press OK");
-
+
   // wait for button press
   while(digitalRead(OK_BTN) == LOW);
-  arcturus.time = (float)millis() / 86400000.0f * 2.0 * M_PI;
-  arcturus.az = azMultiplier * azEncoder.read();
-  arcturus.alt = altMultiplier * altEncoder.read();
+  alignmentStar2.time = (float)millis() / 86400000.0f * 2.0 * M_PI;
+  alignmentStar2.az = azMultiplier * azEncoder.read();
+  alignmentStar2.alt = altMultiplier * altEncoder.read();

   lcd.clear();
   lcd.print("Alt set: ");
-  lcd.print(arcturus.alt * rad2deg, 3);
+  lcd.print(alignmentStar2.alt * rad2deg, 3);
   lcd.setCursor(0,1);
   lcd.print("Az set: ");
-  lcd.print(arcturus.az * rad2deg, 3);
+  lcd.print(alignmentStar2.az * rad2deg, 3);

   delay(2000);
 }

 void calculateTransforms() {
-  // calculate vectors for aAnd and aUmi
-  fillVectorWithT(firstTVector, rigelK.alt, rigelK.az);
-  fillVectorWithT(secondTVector, arcturus.alt, arcturus.az);
-
+  // calculate vectors for alignment stars
+  fillVectorWithT(firstTVector, alignmentStar1.alt, alignmentStar1.az);
+  fillVectorWithT(secondTVector, alignmentStar2.alt, alignmentStar2.az);
+
   // calculate third's vectors
   fillVectorWithProduct(thirdTVector, firstTVector, secondTVector);

-  // calculate celestial vectors for aAnd and aUmi
-  fillVectorWithC(firstCVector, rigelK, initialTime);
-  fillVectorWithC(secondCVector, arcturus, initialTime);
-
+  // calculate celestial vectors for alignment stars
+  fillVectorWithC(firstCVector, alignmentStar1, initialTime);
+  fillVectorWithC(secondCVector, alignmentStar2, initialTime);
+
   // calculate third's vector
   fillVectorWithProduct(thirdCVector, firstCVector, secondCVector);
-
+
   fillMatrixWithVectors(telescopeMatrix, firstTVector, secondTVector, thirdTVector);
-  fillMatrixWithVectors(celestialMatrix, firstCVector, secondCVector, thirdCVector);
-
+  fillMatrixWithVectors(celestialMatrix, firstCVector, secondCVector, thirdCVector);
+
   copyMatrix(inverseMatrix, celestialMatrix);
   invertMatrix(inverseMatrix);
-
+
   fillMatrixWithProduct(transformMatrix, telescopeMatrix, inverseMatrix, 3, 3, 3);
   copyMatrix(inverseTransformMatrix, transformMatrix);
   invertMatrix(inverseTransformMatrix);
@@ -384,7 +380,7 @@
   character = Serial.read();
   if (state == WAITING_FOR_START)
   {
-    if (START_CHAR == character)
+    if (character == START_CHAR)
     {
       state = WAITING_FOR_END;
       command = "";
@@ -393,7 +389,7 @@
     }
   } else if (state == WAITING_FOR_END)
   {
-    if (END_CHAR == character)
+    if (character == END_CHAR)
     {
       lcd.setCursor(15,0);
       lcd.print((char)127);
@@ -447,7 +443,7 @@
   float minutes = (degs - floor(degs)) * 60.0;
   String sign = "+";
   if (rad < 0) sign = "-";
-
+
   if (highPrecision)
   {
     return sign + padding((String)int(floor(degs)), 2) + "*" + padding((String)int(floor(minutes)), 2) + ":" + padding((String)int(floor((minutes - floor(minutes)) * 60.0)), 2);
@@ -471,3 +467,19 @@
   lcd.setCursor(0, 1);
   lcd.print("Dec:  ");
 }
+
+void printMatrix(float* m)
+{
+  // apparently I deleted the print matrix function, so I'm adding this back in
+  // so debug doesn't die.
+
+  // TODO: rewrite printMatrix.
+}
+
+void printVector(float* v)
+{
+  // apparently I deleted the print vector function, so I'm adding this back in
+  // so debug doesn't die.
+
+  // TODO: rewrite printVector.
+}


Removed redundant heartbeat::start

Removed redundant heartbeat::start

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -84,10 +84,8 @@
   Serial.print(F("Sensor pressure reading: "));
   Serial.println(sensor_data.pressure);

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

   // try to send 5 times, if 5 fail restart the module


Added serial print for succesfull data transmission

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -96,6 +96,8 @@
 			// Make our heartbeat LED blink at a normal rate again if we were panicking earlier.
 			Heartbeat::start();

+			Serial.println(F("Sensor data was sent to the server succesfully!"));
+
 			break;
 		}
 	}


some refactoring

some refactoring

--- sketches/Energino2/Energino2.ino
+++ sketches/Energino2/Energino2.ino
@@ -54,7 +54,7 @@
 #include <avr/eeprom.h>

 // comment/uncomment to disable/enable debug
-#define DEBUG
+//#define DEBUG

 #define RELAY_PIN 3
 #define STRING_BUFFER_SIZE 300
@@ -164,13 +164,14 @@
 }

 void setup() {
+  // Set serial port
+  Serial.begin(115200);
   // Default on
   pinMode(RELAY_PIN,OUTPUT);
   digitalWrite(RELAY_PIN, LOW);
   pinMode(13,OUTPUT);
   digitalWrite(13, LOW);
   // configuring serial
-  Serial.begin(115200);
   // Loading setting
   eeprom_read_block((void*)&settings, (void*)0, sizeof(settings));
   if (strcmp(settings.magic, MAGIC) != 0) {
@@ -185,12 +186,16 @@
   DBG Serial.print("HWAddr: ");
   DBG Serial.println(macstr);
   // Try to configure the ethernet using DHCP
+  delay(2000);
   DBG Serial.println("Running DHCP...");
   if (Ethernet.begin(settings.mac) == 0) {
     DBG Serial.println("DHCP failed, using static IP.");
     // Use static IP
     Ethernet.begin(settings.mac, IP, MASK, GW);
   }
+  // Print IP
+  DBG Serial.print("IPAddr: ");
+  DBG Serial.println(Ethernet.localIP());
   // Give the Ethernet shield a second to initialize:
   delay(1000);
   // Start server
@@ -232,6 +237,9 @@

   // send data to remote host
   sendData();
+
+  // dump to serial
+  dumpToSerial();

   // Control loop
   delta = abs(millis() - started);
@@ -364,17 +372,18 @@
       // If you've gotten to the end of the line (received a newline
       // character) the http request has ended, so you can send a reply
       if (c == '\n' || idx >= STRING_BUFFER_SIZE) {
-        char method [5];
-        char url [20];
-        sscanf (buffer,"%s /%s/%s/%d",method,url);
+        //char method [5];
+        char * method;
+        method = strtok (buffer, " ");
         if (strcmp(method, "GET") == 0) {
           char * toks;
-          toks = strtok (url,"/");
+          toks = strtok (NULL," ");
+          toks = strtok (toks,"/");
           if (strcmp(toks, "read") == 0) {
             toks = strtok (NULL, "/");
             if (strcmp(toks, "datastreams") == 0) {
               DBG Serial.println("Sending full datastream");
-              sendContent(request,getDatastreams());
+              sendContent(request,getDatastream());
               break;
             }
             else if (strcmp(toks, "switch") == 0) {
@@ -416,22 +425,8 @@
   }
 }

-void sendContent(EthernetClient &request, long value) {
-  request.println(JSON_RESPONSE_BEGIN);
-  request.print(value);
-  request.print(JSON_RESPONSE_END);
-}
-
-void sendContent(EthernetClient &request, char *value) {
-  request.println(JSON_RESPONSE_BEGIN);
-  request.print(value);
-  request.print(JSON_RESPONSE_END);
-}
-
 // this method makes a HTTP connection to the server
 void sendData() {
-  // poll energino
-  char *json = getDatastreams();
   // check if the feed has been initialized
   if (settings.feed == 0) {
     return;
@@ -439,7 +434,10 @@
   // try to connect
   DBG Serial.println("Connecting.");
   EthernetClient client;
-  if (client.connect(settings.host, settings.port)) {
+  int ret = client.connect(settings.host, settings.port);
+  if (ret == 1) {
+    // build json document
+    char *json = getDatastream();
     DBG Serial.println("connected.");
     DBG Serial.print("PUT /v2/feeds/");
     DBG Serial.println(settings.feed);
@@ -452,8 +450,7 @@
     client.print("User-Agent: ");
     client.println(MAGIC);
     client.print("Content-Length: ");
-    client.print(strlen(json));
-    client.print("\n");
+    client.println(strlen(json));
     client.print("Content-Type: application/json\n");
     client.print("\n");
     // here's the actual content of the PUT request:
@@ -474,7 +471,19 @@
   }
 }

-char * getDatastreams() {
+void sendContent(EthernetClient &request, long value) {
+  request.println(JSON_RESPONSE_BEGIN);
+  request.print(value);
+  request.print(JSON_RESPONSE_END);
+}
+
+void sendContent(EthernetClient &request, char *value) {
+  request.println(JSON_RESPONSE_BEGIN);
+  request.print(value);
+  request.print(JSON_RESPONSE_END);
+}
+
+char * getDatastream() {
   strcpy (buffer,"{\"version\":\"1.0.0\",");
   strcat (buffer,"\"datastreams\":[");
   strcat (buffer,"{\"id\":\"current\",\"current_value\":");
@@ -490,6 +499,9 @@
   strcat (buffer,itoa(digitalRead(RELAY_PIN),r,10));
   strcat (buffer,"}");
   strcat (buffer,"]}");
+}
+
+void dumpToSerial() {
   // Print data also on the serial
   Serial.print("#");
   Serial.print(MAGIC);
@@ -526,7 +538,7 @@
   Serial.print(",");
   Serial.print(settings.apikey);
   Serial.print("\n");
-  return buffer;
+
 }

 float scaleVoltage(float VRaw) {


main_ar.ino: adding different phases to test LED fading

--- projects/main_ar/main_ar.ino
+++ projects/main_ar/main_ar.ino
@@ -14,9 +14,9 @@
 }

 int f1 = 0;
-int f2 = 0;
-int f3 = 0;
-int f4 = 0;
+int f2 = 10;
+int f3 = 20;
+int f4 = 30;

 void loop() {
   leds.setRgbColor(0, func(f1), func(f2), func(f3));


Removed bug on short buffer, maybe

Removed bug on short buffer, maybe

--- core.ino
+++ core.ino
@@ -8,11 +8,15 @@
 int inDataBufferLen[CHANNELS];
 boolean httpRequestRead[CHANNELS];

+boolean open[CHANNELS];
+
 unsigned char state = 0;

 Stream* espStream = &ESP_SERIAL;

 boolean debugPrevNoData = false;
+
+boolean unread = false;

 void setup() {
   //softSerial.begin(9600);
@@ -27,39 +31,47 @@
   inBuffer[0]=0; // USELESS
   for (int i=0; i < CHANNELS; i++) {
     inDataBufferLen[i]=0;
-    inDataBuffer[i][0]=0; // USELESS
+    inDataBuffer[i][0]=0;
+    open[i]=false;
   }
 }

 int readLineLowLevel() {
-  inBufferLen = 0;
-  if (!espStream->available()) {
-    inBufferLen=0;
-    inBuffer[0]=0;
-    return 0;
-  }
+  if (!unread) {
+    inBufferLen = 0;
+    if (!espStream->available()) {
+      inBuffer[inBufferLen]=0;
+      return 0;
+    }
+  }
+  unread=false;
+  //DEBUG_SERIAL.print("LL READ: {");
   // Read to in buffer
-  int prev = -1;
   int i = 0;
-  //DEBUG_SERIAL.print("LL READ: {");
   while (true) {
+    if (inBufferLen >= 2 && inBuffer[inBufferLen-2] == '\r' && inBuffer[inBufferLen-1] == '\n') {
+      break;
+    }
     while(!espStream->available());
     char c = espStream->read();
+    i++;
     //DEBUG_SERIAL.print(c);
-    i++;
+    //DEBUG_SERIAL.print(c, HEX);
     if (inBufferLen < BUFFER_SIZE) {
       inBuffer[inBufferLen++] = c;
-    }
-    if (c == '\n' && prev == '\r') {
-      break;
-    }
-    prev = c;
+    } else {
+      if (c == '\r') {
+        inBufferLen = BUFFER_SIZE - 2;
+        inBuffer[inBufferLen++] = c;
+      }
+    }
   }
   //DEBUG_SERIAL.println("}");
   inBuffer[inBufferLen] = 0;
-  //DEBUG_SERIAL.print("RECV: {");
-  //DEBUG_SERIAL.print(inBuffer);
-  //DEBUG_SERIAL.println("}");
+  DEBUG_SERIAL.print("RECV: {");
+  DEBUG_SERIAL.print(inBuffer);
+  DEBUG_SERIAL.println("}");
+  return i;
 }

 boolean ok = false;
@@ -80,7 +92,7 @@
     delay(5);
   }
   boolean data = espStream->available();
-  DEBUG_SERIAL.print(data?"WAIT -> DATA\r\n":debugPrevNoData?"":"WAIT -> NO DATA\r\n");
+  //DEBUG_SERIAL.print(data?"WAIT -> DATA\r\n":debugPrevNoData?"":"WAIT -> NO DATA\r\n");
   debugPrevNoData = !data;
   return data;
 }
@@ -110,7 +122,7 @@
   readLine();
   readLine();
   boolean ok = (inBufferLen == 4 && memcmp(inBuffer, "OK\r\n", 4) == 0);
-  DEBUG_SERIAL.println(ok?"OK":"NOT OK");
+  //DEBUG_SERIAL.println(ok?"OK":"NOT OK");
   return ok;
 }

@@ -120,6 +132,7 @@
   inDataBufferLen[n]=0;
   DEBUG_SERIAL.print("Connected ");
   DEBUG_SERIAL.println(n);
+  open[n]=true;
   httpRequestRead[n] = false;
   userConnect(n);
 }
@@ -128,6 +141,7 @@
   int n = inBuffer[0] - '0';
   DEBUG_SERIAL.print("Closed ");
   DEBUG_SERIAL.println(n);
+  open[n]=false;
   userClosed(n);
 }

@@ -136,6 +150,12 @@
    * Do not respond unless inDataBuffer[n] equals "\r\n" (empty line)
    */
   DEBUG_SERIAL.print("+IPD LINE: ");
+  DEBUG_SERIAL.print(n);
+  DEBUG_SERIAL.print(" : ");
+  if (!open[n]) {
+    DEBUG_SERIAL.println("ERROR. NOT CONNECTED");
+    return;
+  }
   DEBUG_SERIAL.println(inDataBuffer[n]);
   if (strcmp(inDataBuffer[n], "\r\n") != 0) {
     if (httpRequestRead[n] == false) {
@@ -154,7 +174,7 @@
   }
 }

-void processIPD() {
+void processIPD(int chars) {
   /*
    * FIXME: There is something broken here. When a line is too long it should crop it and continue but it does not continue correctly.
    */
@@ -182,24 +202,15 @@
     DEBUG_SERIAL.println(inBuffer);
     return;
   }
-  //DEBUG_SERIAL.print("+IPD LL: {{");
+  DEBUG_SERIAL.print("+IPD LL: {{");
   int dp = inDataBufferLen[n];
   int pc = -1;
   int i = j;
   int t = 0;
+  if (chars > BUFFER_SIZE) {
+    t += chars - BUFFER_SIZE;
+  }
   while (t < l) {
-    if (i >= BUFFER_SIZE) {
-        //DEBUG_SERIAL.println();
-        if (inDataBufferLen[n] > 0) {
-          processIPDLine(n);
-        }
-        inDataBuffer[n][0]=0;
-        inDataBufferLen[n]=0;
-        readLineLowLevel();
-        dp = 0;
-        pc = -1;
-        i = -1;
-    }
     if (i > inBufferLen) { //i < IN_BUFFER_SIZE &&
       DEBUG_SERIAL.print("+IPD ERROR: i (");
       DEBUG_SERIAL.print(i);
@@ -213,23 +224,29 @@
       return;
     }
     if (inBufferLen == 0) {
-      readLineLowLevel();
+      chars = readLineLowLevel();
+      if (chars > BUFFER_SIZE) {
+        t += chars - BUFFER_SIZE;
+      }
     } else {
       char c = inBuffer[i];
-      //DEBUG_SERIAL.print(c);
+      DEBUG_SERIAL.print(c);
       if (dp < BUFFER_SIZE) {
         inDataBuffer[n][dp]=c;
         inDataBuffer[n][dp+1]=0;
         dp++;
+        inDataBufferLen[n]=dp;
       }
-      inDataBufferLen[n]=dp;
       if (c == '\n' && pc == '\r') {
         if (inDataBufferLen[n] > 0) {
           processIPDLine(n);
         }
         inDataBuffer[n][0]=0;
         inDataBufferLen[n]=0;
-        readLineLowLevel();
+        chars = readLineLowLevel();
+        if (chars > BUFFER_SIZE) {
+          t += chars - BUFFER_SIZE;
+        }
         dp = 0;
         pc = -1;
         i = -1;
@@ -239,7 +256,7 @@
       t++;
     }
   }
-  //DEBUG_SERIAL.println("}}");
+  DEBUG_SERIAL.println("}}");
 }

 int readLine() {
@@ -248,7 +265,7 @@
   while (!ok) {
     n = readLineLowLevel();
     if (strstr(inBuffer, "+IPD,") == inBuffer) {
-      processIPD();
+      processIPD(n);
     } else if (strstr(inBuffer, ",CONNECT") == &inBuffer[1]) {
       processConnect();
     } else if (strstr(inBuffer, ",CLOSED") == &inBuffer[1]) {
@@ -264,14 +281,14 @@
 }

 void netsend_P(int n, PGM_P str) {
-  //DEBUG_SERIAL.println("NSP");
+  DEBUG_SERIAL.println("NSP");
   char buff[BUFFER_SIZE+1];
   strcpy_P(buff, str);
   netsend(n, buff);
 }

 void netsend(int n, char* str) {
-  //DEBUG_SERIAL.println("NSLL");
+  DEBUG_SERIAL.println("NSLL");
   boolean ok = false;
   while (!ok) {
     while(waitData(50)) {


Update Firmware.ino

Update Firmware.ino

--- src/piggy_back_loggers/SD_prototype_Firmware/Firmware/Firmware.ino
+++ src/piggy_back_loggers/SD_prototype_Firmware/Firmware/Firmware.ino
@@ -92,7 +92,7 @@
   * If button is pressed (active-low):
   *   Set serialOn flag.
   \*****************************************/
-  if(digitalRead(5) == 0)
+  if((digitalRead(5) == 0) && !State.serialOn)
   {
     State.serialOn = true;
     serialPowerUp();


Fixed type

Fixed type

--- module/module.ino
+++ module/module.ino
@@ -39,8 +39,8 @@
 void loop() {
 	// some variables
 	int8_t isStaff, isAuthorized, isValidResponse = 0;
-	int16_t userID, totalTime = 0;
-	unsigned long existingTime, elapsedTime = 0;
+	int16_t userID = 0;
+	unsigned long existingTime, elapsedTime, totalTime = 0;
 	unsigned char readData[bufferSize];
 	// ----------------------------------------------------------------------
 	// Turn LED off, lock laser cutter
@@ -367,4 +367,4 @@
 			digitalWrite(supportPin, LOW);
 		}
 	}
-}+}


Changed variable name

Changed variable name

--- module/module.ino
+++ module/module.ino
@@ -135,7 +135,7 @@
 /*
 	This function monitors the motor driver signals on the laser cutter.
 	The signals are PWMs of a specific frequency. This function measures the
-	half-period of any signal detected and accumulates time when valid signals
+	period of any signal detected and accumulates time when valid signals
 	are detected. A polling subroutine continuously checks if an RFID tag is
 	still present.

@@ -146,7 +146,7 @@
 	// some constants
 	const int pollTimeout = 5;
 	const int pollInterval = 900;
-	const int minCount = 5;
+	const int freeTime = 5;
 	// some variables used in this scope
 	unsigned char serialNumber[bufferSizeSNR];
 	unsigned long startTime, elapsedTime = 0;
@@ -174,7 +174,7 @@
 				elapsedTime = calculateTime(startTime);

 				// Any valid accumulated time will be returned
-				if (startTime > 0 && elapsedTime > minCount) {
+				if (startTime > 0 && elapsedTime > freeTime) {
           			return elapsedTime;
 				}
 				else {
@@ -226,7 +226,7 @@
 			// so, if lastPeriodX and lastPeriodY WAS a valid pair
 			/*if ( inRange(lastPeriodX, lastPeriodY) ) {
 				// check if the job was more than 5 seconds
-				if (pulseCount > minCount) {
+				if (pulseCount > freeTime) {
 					// calculate elapsed time in seconds
 					return calculateTime(startTime);
 				}
@@ -236,7 +236,9 @@
 			// check if enough negative signals have been detected
 			if (checkHistory(signals) == flag.detectedJobEnd) {
 				elapsedTime = calculateTime(startTime);
-				if (startTime > 0 && elapsedTime > minCount) {
+
+				// check if a job was detected
+				if (startTime > 0 && elapsedTime > freeTime) {
 					return elapsedTime;
 				}
 				else {


updated LCD display

updated LCD display

--- mwsLCD/mwsLCD.ino
+++ mwsLCD/mwsLCD.ino
@@ -515,12 +515,12 @@
   Serial.print(gps.satellites.value());

   lcd.clear();
-  lcd.print("Longitude (dd.ddd)");
+  lcd.print("Longitude (dd.d)");
   lcd.setCursor(0, 2);
   lcd.print(gps.location.lng(), 6);
   delay(2000);
   lcd.clear();
-  lcd.print("Latitude (dd.ddd)");
+  lcd.print("Latitude (dd.d)");
   lcd.setCursor(0, 2);
   lcd.print(gps.location.lat(), 6);
   delay(2000);
@@ -555,7 +555,7 @@
   Serial.print(windspeedms, 1);

   lcd.clear();
-  lcd.print("Wind Direction (dd.ddd)");
+  lcd.print("Wind Direction");
   lcd.setCursor(0, 2);
   lcd.print(winddir);
   delay(2000);
@@ -566,9 +566,6 @@
   lcd.print(windspeedms);
   delay(2000);

-
-
-
   //Serial.print(",windgustms=");
   Serial.print(",");
   Serial.print(windgustms, 1);
@@ -593,6 +590,20 @@
   //Serial.print(",tempc=");
   Serial.print(",");
   Serial.print(tempf, 1);
+
+
+  lcd.clear();
+  lcd.print("Humidity (%)");
+  lcd.setCursor(0, 2);
+  lcd.print(humidity);
+  delay(2000);
+
+  lcd.clear();
+  lcd.print("Temperature (Celsius)");
+  lcd.setCursor(0, 2);
+  lcd.print(tempf);
+  delay(2000);
+
   //Serial.print(",raindailymm=");
   Serial.print(",");
   Serial.print(dailyrainin, 2);


Increased display of info to 5 seconds

Increased display of info to 5 seconds

--- mwsLCD/mwsLCD.ino
+++ mwsLCD/mwsLCD.ino
@@ -181,22 +181,22 @@
   myPressure.setOversampleRate(7); // Set Oversample to the recommended 128
   myPressure.enableEventFlags(); // Enable all three pressure and temp event flags

-    //Configure the humidity sensor
+  //Configure the humidity sensor
   myHumidity.begin();
-
+
+  // attach external interrupt pins to IRQ functions
+  attachInterrupt(0, rainIRQ, FALLING);
+  attachInterrupt(1, wspeedIRQ, FALLING);
+
+  // turn on interrupts
+  interrupts();
+
   smartdelay(60000); //Wait 60 seconds, and gather GPS data
   minutes = gps.time.minute();
   //minutes_5m = gps.time.minute();
   minutes_10m = gps.time.minute();
   seconds = gps.time.second();
   lastSecond = millis();
-  // attach external interrupt pins to IRQ functions
-  attachInterrupt(0, rainIRQ, FALLING);
-  attachInterrupt(1, wspeedIRQ, FALLING);
-
-  // turn on interrupts
-  interrupts();
-
 }

 void loop()
@@ -486,17 +486,17 @@
   sprintf(sz, "%02d:%02d:%02d", gps.time.hour(), gps.time.minute(), gps.time.second());
   lcd.print(sz);
   lcd.print(" GMT");
-  delay(4000);
+  delay(5000);

   lcd.clear();
   lcd.print("WD: ");
   lcd.print(get_wind_direction());
-  lcd.print("  N=0 CW");
+  lcd.print(" N=0 CW");
   lcd.setCursor(0, 2);
   lcd.print("WS:");
   lcd.print(get_wind_speed(), 1);
   lcd.print(" m/s");
-  delay(4000);
+  delay(5000);

   lcd.clear();
   lcd.print("H:");
@@ -506,7 +506,7 @@
   lcd.print("T:");
   lcd.print(myPressure.readTemp());
   lcd.print(" C");
-  delay(4000);
+  delay(5000);

   //Not enough dynamic memory in UNO
   //lcd.clear();
@@ -523,7 +523,7 @@
   lcd.print("P:");
   lcd.print(myPressure.readPressure()/100.0);
   lcd.print(" hPa");
-  delay(4000);
+  delay(5000);

   //Not enough dynamic memory in UNO
   //lcd.clear();


Adding serial port reading for cocoa.

Adding serial port reading for cocoa.

--- receiver/receiver.ino
+++ receiver/receiver.ino
@@ -8,7 +8,7 @@
 const int role_pin = 6;
 const int sensor_pin = 3;
 const int led_pin = 4;
-const uint64_t pipe = 0xE8E8F0F0E1LL;
+const uint64_t pipe = 0xE8E8F0F0F1LL;

 typedef enum {
     role_remote = 1,
@@ -23,7 +23,7 @@
 void setup(void) {
     // set up the role pin
     pinMode(role_pin, INPUT);
-    digitalWrite(role_pin,HIGH);
+    digitalWrite(role_pin, HIGH);
     delay(20); // Just to get a solid reading on the role pin

     // read the address pin, establish our role
@@ -31,7 +31,7 @@

     Serial.begin(57600);
     printf_begin();
-    printf("\n\rRF24/examples/led_remote/\n\r");
+    Serial.print("\n\rRF24/examples/led_remote/\n\r");
     printf("ROLE: %s\n\r",role_friendly_name[role]);

     radio.begin();
@@ -55,8 +55,16 @@

     // Turn LED's ON until we start getting keys
     pinMode(led_pin,OUTPUT);
-    led_state = HIGH;
+    led_state = LOW;
     digitalWrite(led_pin, led_state);
+    int i = role == role_led ? 4 : 2;
+    int pause = role == role_led ? 100 : 300;
+    while (i--) {
+        delay(pause);
+        digitalWrite(led_pin, HIGH);
+        delay(pause);
+        digitalWrite(led_pin, LOW);
+    }
 }

 void loop(void) {
@@ -100,5 +108,18 @@
                 digitalWrite(led_pin, led_state);
             }
         }
+
+        uint8_t incomingByte;
+        // send data only when you receive data:
+	if (Serial.available() > 0) {
+            // read the incoming byte:
+            incomingByte = Serial.read();
+
+            // say what you got with both the ASCII and decimal representations
+            Serial.print("I received: ");
+            Serial.write(incomingByte);
+            Serial.print(" : ");
+            Serial.println(incomingByte, DEC);
+	}
     }
 }


Removed starting logic

Removed starting logic

Preivously one of our fridges needed the ability to have a starter pin
active for a given amount of time, and we also checked for errors to
avoid overheating. This is no longer needed. So feature removed for
simplicity.


renamed include

renamed include

--- firmware/examples/VCNL4010-tester.ino
+++ firmware/examples/VCNL4010-tester.ino
@@ -1,7 +1,7 @@
 // This #include statement was automatically added by the Particle IDE.
-#include "particle-vcnl4010.h"
+#include "VCNL4010.h"

-particle-vcnl4010 vcnl;
+vcnl4010 vcnl;

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


Make fire more realistic

Make fire more realistic

--- cauldron/cauldron.ino
+++ cauldron/cauldron.ino
@@ -119,16 +119,16 @@
   // The fan cycles between 50% and 100% every 5 seconds
   fan->enabled = false;
   fan->minimum = 0xff;
-  fan->maximum = 0x80;
+  fan->maximum = 0xc0;
   fan->time = 5000;
   fan->step = 0;
   fan->delta = 1;

-  // The fire cycles between 50% and 100% every 250ms
+  // The fire
   fire->enabled = false;
-  fire->minimum = 0x80;
+  fire->minimum = 0x20;
   fire->maximum = 0xff;
-  fire->time = 250;
+  fire->time = 500;
   fire->step = 0;
   fire->delta = 1;

@@ -205,10 +205,18 @@
   }

   if (fire->enabled) {
-    uint32_t value = interpolateValue(fire);
-    analogWrite(PWM_RED, (uint8_t)value);
-
-    stepCycle(fire);
+    if (fire->step++ == fire->time) {
+      uint8_t value = random(fire->minimum, fire->maximum) & 0xe0;
+      analogWrite(PWM_RED, value);
+
+      fire->step = 0;
+      fire->time = random(20, 100);
+    }
+
+//    uint32_t value = interpolateValue(fire);
+//    analogWrite(PWM_RED, (uint8_t)value);
+
+//    stepCycle(fire);
   }

   if (glow->enabled) {


similatore concluso

similatore concluso

--- mqtt_simulatore_eth/mqtt_simulatore_eth.ino
+++ mqtt_simulatore_eth/mqtt_simulatore_eth.ino
@@ -31,8 +31,8 @@

 // Update these with values suitable for your network.
 byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
-IPAddress ip(192, 168, 1, 101);
-IPAddress server(192, 168, 1, 69);
+IPAddress ip(192, 168, 1, 230);
+IPAddress server(192, 168, 1, 145);

 void callback(char* topic, byte* payload, unsigned int length) {
   Serial.print("Message arrived [");
@@ -92,7 +92,19 @@
   temp = String(random(-40,50));
   terUm = String(random(0, 1024));
   AriaUm = String(random(0, 1024));
-  timeAcq = String(random(1,31)) + "/"+ String(random(1,13)) + "/" + String(2018);
+  //YYYY-MM-dd hh:mm:ss
+  String MM = '0' + String(random(1,13));
+  MM = MM.substring(MM.length() - 2, MM.length());
+  String dd = '0' + String(random(1,32));
+  dd = dd.substring(dd.length() - 2, dd.length());
+  String hh = '0' + String(random(0,24));
+  hh = hh.substring(hh.length() - 2, hh.length());
+  String mm = '0' + String(random(0,60));
+  mm = mm.substring(mm.length() - 2, mm.length());
+  String ss = '0' + String(random(0,60));
+  ss = ss.substring(ss.length() - 2, ss.length());
+  timeAcq =  (String)2018 + '-' + MM + "-" + dd + " " + \
+              hh + ":" + mm + ":" + ss;

   String msg= puntoAcq + ',' + temp + ',' + terUm + ',' + AriaUm + ',' + timeAcq;


use period constant

use period constant

--- sketches/EnerginoPOE/EnerginoPOE.ino
+++ sketches/EnerginoPOE/EnerginoPOE.ino
@@ -74,7 +74,7 @@
 int R2 = 100;
 int OFFSET = 2500;
 int SENSITIVITY = 185;
-int PERIOD = 2000;
+int PERIOD = 5000;

 // magic string
 const char MAGIC[] = "EnerginoPOE";
@@ -143,10 +143,9 @@

 void loop() {
   // Make sure that update period is not too high
-  // when pushing data to Xively (one sample every
-  // 2 seconds should be a reasonable lower boud)
-  if ((settings.feedid != 0) && (settings.period < 2000)) {
-    settings.period = 2000;
+  // when pushing data to Xively
+  if ((settings.feedid != 0) && (settings.period < PERIOD)) {
+    settings.period = PERIOD;
   }
   // Get clients coming from server
   YunClient client = server.accept();


Update RangeSingleShot.ino

Update RangeSingleShot.ino

--- firmware/examples/RangeSingleShot.ino
+++ firmware/examples/RangeSingleShot.ino
@@ -3,7 +3,7 @@

 The range readings are in units of mm. */

-#include <vl6180x_lib.h>
+#include "vl6180x_lib/vl6180x_lib.h"

 VL6180X sensor;


replace last for loop by ranged-for

replace last for loop by ranged-for

--- ksp-gegi/ksp-gegi.ino
+++ ksp-gegi/ksp-gegi.ino
@@ -33,7 +33,6 @@
   digitalPin(5,0,0,7),    // low power
   digitalPin(6,0,0,3)     // low fuel
 };
-const uint8_t ndigiPins = (sizeof(digiPins) / sizeof(digiPins[0]));

 digitalPin::digitalPin(const uint8_t id, const uint8_t pinSwitch, const uint8_t pinOn, const uint8_t pinOff) :
   m_id(id), m_pinSwitch(pinSwitch), m_pinOn(pinOn), m_pinOff(pinOff)
@@ -252,8 +251,8 @@
 	  blink = true;
 	  lastBlink = currentMillis;
   }
-  for (uint8_t i = 0; i < ndigiPins; ++i) {
-    digiPins[i].updateLed(blink);
+  for (auto &p : digiPins) {
+    p.updateLed(blink);
   }
 }


update example

update example

--- examples/threshold/threshold.ino
+++ examples/threshold/threshold.ino
@@ -1,8 +1,6 @@
 #include <Helper2.h>
-#include <Wire.h>
-#include <TimerOne.h>
-
-int incomingByte = 0;
+// #include <Wire.h>
+// #include <TimerOne.h>

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


FeatureDemo: added support for colour spaces

--- examples/FeatureDemo/FeatureDemo.ino
+++ examples/FeatureDemo/FeatureDemo.ino
@@ -203,14 +203,18 @@
             float fraction = ((float)millis() - currentMillis) / ((float)transitionTime / 2);

             if (millis() - currentMillis < transitionTime / 2) {
-                color.red = 255 - 255.0 * fraction;
-                color.green = 255.0 * fraction;
-                color.blue = 0;
+                color = {
+                  (uint8_t)(255 - 255.0 * fraction),
+                  (uint8_t)(255.0 * fraction),
+                  0
+                };
             }
             else {
-                color.red = 0;
-                color.green = 255 - 255.0 / 2 * (fraction - 1.0);
-                color.blue = 255.0 * (fraction - 1.0);
+                color = {
+                  0,
+                  (uint8_t)(255 - 255.0 / 2 * (fraction - 1.0)),
+                  (uint8_t)(255.0 * (fraction - 1.0))
+                };
             }

             for (i = 0; i < 20; i++) {
@@ -244,9 +248,11 @@
             rgb24 color;
             float fraction = ((float)millis() - currentMillis) / ((float)transitionTime / 2);

-            color.red = 255 - 255.0 * fraction;
-            color.green = 255.0 * fraction;
-            color.blue = 0;
+            color = {
+              (uint8_t)(255 - 255.0 * fraction),
+              (uint8_t)(255.0 * fraction),
+              0
+            };

             matrix.drawFastVLine(i, 0, matrix.getScreenHeight(), color);
             matrix.swapBuffers(true);
@@ -260,9 +266,11 @@
             fraction -= 1.0;
             if (fraction < 0) fraction = 0.0;

-            color.red = 0;
-            color.green = 255 - 255.0 / 2 * (fraction);
-            color.blue = 255.0 * (fraction);
+            color = {
+              0,
+              (uint8_t)(255 - 255.0 / 2 * (fraction)),
+              (uint8_t)(255.0 * (fraction))
+            };

             matrix.drawFastHLine(0, matrix.getScreenWidth(), i, color);
             matrix.swapBuffers(true);
@@ -280,9 +288,11 @@
             rgb24 color;
             float fraction = ((float)millis() - currentMillis) / ((float)transitionTime / 2);

-            color.red = 255 - 255.0 * fraction;
-            color.green = 255.0 * fraction;
-            color.blue = 0;
+            color = {
+              (uint8_t)(255 - 255.0 * fraction),
+              (uint8_t)(255.0 * fraction),
+              0
+            };

             matrix.drawLine(i, 0, 0, i, color);
             matrix.swapBuffers(true);
@@ -296,9 +306,11 @@
             fraction -= 1.0;
             if (fraction < 0) fraction = 0.0;

-            color.red = 0;
-            color.green = 255 - 255.0 / 2 * (fraction);
-            color.blue = 255.0 * (fraction);
+            color = {
+              0,
+              (uint8_t)(255 - 255.0 / 2 * (fraction)),
+              (uint8_t)(255.0 * (fraction))
+            };

             matrix.drawLine(0, matrix.getScreenHeight() - i, matrix.getScreenWidth(), i, color);
             matrix.swapBuffers(true);
@@ -328,9 +340,11 @@
             rgb24 color;
             float fraction = ((float)millis() - currentMillis) / ((float)transitionTime / 2);

-            color.red = 255 - 255.0 * fraction;
-            color.green = 255.0 * fraction;
-            color.blue = 0;
+            color = {
+              (uint8_t)(255 - 255.0 * fraction),
+              (uint8_t)(255.0 * fraction),
+              0
+            };

             matrix.drawTriangle(i, 0, matrix.getScreenWidth(), i, matrix.getScreenWidth() - i, matrix.getScreenHeight(), color);
             matrix.swapBuffers(true);
@@ -344,9 +358,11 @@
             fraction -= 1.0;
             if (fraction < 0) fraction = 0.0;

-            color.red = 0;
-            color.green = 255 - 255.0 / 2 * (fraction);
-            color.blue = 255.0 * (fraction);
+            color = {
+              0,
+              (uint8_t)(255 - 255.0 / 2 * (fraction)),
+              (uint8_t)(255.0 * (fraction))
+            };

             matrix.drawTriangle(matrix.getScreenWidth() - i, matrix.getScreenHeight(), 0, matrix.getScreenHeight() - i, matrix.getScreenWidth(), i, color);
             matrix.swapBuffers(true);
@@ -376,9 +392,11 @@
             rgb24 color;
             float fraction = ((float)millis() - currentMillis) / ((float)transitionTime / 2);

-            color.red = 255 - 255.0 * fraction;
-            color.green = 255.0 * fraction;
-            color.blue = 0;
+            color = {
+              (uint8_t)(255 - 255.0 * fraction),
+              (uint8_t)(255.0 * fraction),
+              0
+            };

             int radius = i / 2;
             if (radius > matrix.getScreenWidth())
@@ -396,9 +414,11 @@
             fraction -= 1.0;
             if (fraction < 0) fraction = 0.0;

-            color.red = 0;
-            color.green = 255 - 255.0 / 2 * (fraction);
-            color.blue = 255.0 * (fraction);
+            color = {
+              0,
+              (uint8_t)(255 - 255.0 / 2 * (fraction)),
+              (uint8_t)(255.0 * (fraction))
+            };

             matrix.drawCircle(matrix.getScreenWidth() / 2, matrix.getScreenHeight() / 2, i, color);
             matrix.swapBuffers(true);
@@ -429,9 +449,11 @@
             rgb24 color;
             float fraction = ((float)millis() - currentMillis) / ((float)transitionTime / 2);

-            color.red = 255 - 255.0 * fraction;
-            color.green = 255.0 * fraction;
-            color.blue = 0;
+            color = {
+              (uint8_t)(255 - 255.0 * fraction),
+              (uint8_t)(255.0 * fraction),
+              0
+            };

             matrix.drawRectangle(matrix.getScreenWidth() / 2 - i - 1, matrix.getScreenHeight() / 2 - i - 1, matrix.getScreenWidth() / 2 + i, matrix.getScreenHeight() / 2 + i, color);
             matrix.swapBuffers(true);
@@ -444,9 +466,11 @@
             fraction -= 1.0;
             if (fraction < 0) fraction = 0.0;

-            color.red = 0;
-            color.green = 255 - 255.0 / 2 * (fraction);
-            color.blue = 255.0 * (fraction);
+            color = {
+              0,
+              (uint8_t)(255 - 255.0 / 2 * (fraction)),
+              (uint8_t)(255.0 * (fraction))
+            };

             matrix.drawRectangle(i / 4, i / 2, i, i, color);
             matrix.swapBuffers(true);
@@ -476,9 +500,11 @@
             rgb24 color;
             float fraction = ((float)millis() - currentMillis) / ((float)transitionTime / 2);

-            color.red = 255 - 255.0 * fraction;
-            color.green = 255.0 * fraction;
-            color.blue = 0;
+            color = {
+              (uint8_t)(255 - 255.0 * fraction),
+              (uint8_t)(255.0 * fraction),
+              0
+            };

             matrix.drawRoundRectangle(matrix.getScreenWidth() / 2 - i - 1, matrix.getScreenHeight() / 2 - i - 1, matrix.getScreenWidth() / 2 + i, matrix.getScreenHeight() / 2 + i, i / 2, color);
             matrix.swapBuffers(true);
@@ -491,9 +517,11 @@
             fraction -= 1.0;
             if (fraction < 0) fraction = 0.0;

-            color.red = 0;
-            color.green = 255 - 255.0 / 2 * (fraction);
-            color.blue = 255.0 * (fraction);
+            color = {
+              0,
+              (uint8_t)(255 - 255.0 / 2 * (fraction)),
+              (uint8_t)(255.0 * (fraction))
+            };

             matrix.drawRoundRectangle(i / 4, i / 2, i, i, i / 2, color);
             matrix.swapBuffers(true);
@@ -525,9 +553,11 @@
             rgb24 color;
             float fraction = ((float)millis() - currentMillis) / ((float)transitionTime);

-            color.red = random(256);
-            color.green = random(256);
-            color.blue = 0;
+            color = {
+              (uint8_t)(random(256)),
+              (uint8_t)(random(256)),
+              0
+            };

             if (fraction < 1.0 / 3) {
                 matrix.drawRectangle(random(matrix.getScreenWidth() / 4), random(matrix.getScreenHeight() / 4),
@@ -599,14 +629,18 @@
             float fraction = ((float)millis() - currentMillis) / ((float)transitionTime / 2);

             if (millis() - currentMillis < transitionTime / 2) {
-                color.red = 255 - 255.0 * fraction;
-                color.green = 255.0 * fraction;
-                color.blue = 0;
+                color = {
+                  (uint8_t)(255 - 255.0 * fraction),
+                  (uint8_t)(255.0 * fraction),
+                  0
+                };
             }
             else {
-                color.red = 0;
-                color.green = 255 - 255.0 / 2 * (fraction - 1.0);
-                color.blue = 255.0 * (fraction - 1.0);
+                color = {
+                  0,
+                  (uint8_t)(255 - 255.0 / 2 * (fraction - 1.0)),
+                  (uint8_t)(255.0 * (fraction - 1.0))
+                };
             }

             for (i = 0; i < 20; i++) {
@@ -786,14 +820,18 @@
             float fraction = ((float)millis() - currentMillis) / ((float)transitionTime / 2);

             if (millis() - currentMillis < transitionTime / 2) {
-                color.red = 255 - 255.0 * fraction;
-                color.green = 255.0 * fraction;
-                color.blue = 0;
+                color = {
+                  (uint8_t)(255 - 255.0 * fraction),
+                  (uint8_t)(255.0 * fraction),
+                  0
+                };
             }
             else {
-                color.red = 0;
-                color.green = 255 - 255.0 / 2 * (fraction - 1.0);
-                color.blue = 255.0 * (fraction - 1.0);
+                color = {
+                  0,
+                  (uint8_t)(255 - 255.0 / 2 * (fraction - 1.0)),
+                  (uint8_t)(255.0 * (fraction - 1.0))
+                };
             }

             matrix.setScrollColor(color);
@@ -820,7 +858,7 @@
         while (millis() - currentMillis < transitionTime);

         matrix.setScrollMode(bounceForward);
-        matrix.scrollText("Bounce - Bounce - Bounce - Bounce", 2);
+        matrix.scrollText("Bounce - 12345 - Bounce - 54321", 2);

         transitionTime = 4500 * 4;
         currentMillis = millis();
@@ -1053,9 +1091,11 @@
             extern const bitmap_font weathericon;

             for (i = 0; i < 32 * matrix.getScreenHeight(); i++) {
-                buffer[i].red = weathericon.Bitmap[i * 3 + 0];
-                buffer[i].green = weathericon.Bitmap[i * 3 + 1];
-                buffer[i].blue = weathericon.Bitmap[i * 3 + 2];
+                buffer[i] = {
+                  weathericon.Bitmap[i * 3 + 0],
+                  weathericon.Bitmap[i * 3 + 1],
+                  weathericon.Bitmap[i * 3 + 2]
+                };
             }

             matrix.drawString(12, 16, {0xff, 0, 0}, value);
@@ -1088,9 +1128,11 @@
             extern const bitmap_font weathericon;

             for (i = 0; i < 32 * matrix.getScreenHeight(); i++) {
-                buffer[i].red = weathericon.Bitmap[i * 3 + 0];
-                buffer[i].green = weathericon.Bitmap[i * 3 + 1];
-                buffer[i].blue = weathericon.Bitmap[i * 3 + 2];
+                buffer[i] = {
+                  weathericon.Bitmap[i * 3 + 0],
+                  weathericon.Bitmap[i * 3 + 1],
+                  weathericon.Bitmap[i * 3 + 2]
+                };
             }

             if (j%2) {


Delete HX711Serial.ino

Delete HX711Serial.ino

Remove deprecated example.

--- examples/HX711Serial/HX711Serial.ino
+++ examples/HX711Serial/HX711Serial.ino
@@ -1,56 +0,0 @@
-#include "HX711.h"
-
-// HX711.DOUT	- pin #A1
-// HX711.PD_SCK	- pin #A0
-
-HX711 scale(A1, A0);		// parameter "gain" is ommited; the default value 128 is used by the library
-
-void setup() {
-  Serial.begin(38400);
-  Serial.println("HX711 Demo");
-
-  Serial.println("Before setting up the scale:");
-  Serial.print("read: \t\t");
-  Serial.println(scale.read());			// print a raw reading from the ADC
-
-  Serial.print("read average: \t\t");
-  Serial.println(scale.read_average(20));  	// print the average of 20 readings from the ADC
-
-  Serial.print("get value: \t\t");
-  Serial.println(scale.get_value(5));		// print the average of 5 readings from the ADC minus the tare weight (not set yet)
-
-  Serial.print("get units: \t\t");
-  Serial.println(scale.get_units(5), 1);	// print the average of 5 readings from the ADC minus tare weight (not set) divided
-						// by the SCALE parameter (not set yet)
-
-  scale.set_scale(2280.f);                      // this value is obtained by calibrating the scale with known weights; see the README for details
-  scale.tare();				        // reset the scale to 0
-
-  Serial.println("After setting up the scale:");
-
-  Serial.print("read: \t\t");
-  Serial.println(scale.read());                 // print a raw reading from the ADC
-
-  Serial.print("read average: \t\t");
-  Serial.println(scale.read_average(20));       // print the average of 20 readings from the ADC
-
-  Serial.print("get value: \t\t");
-  Serial.println(scale.get_value(5));		// print the average of 5 readings from the ADC minus the tare weight, set with tare()
-
-  Serial.print("get units: \t\t");
-  Serial.println(scale.get_units(5), 1);        // print the average of 5 readings from the ADC minus tare weight, divided
-						// by the SCALE parameter set with set_scale
-
-  Serial.println("Readings:");
-}
-
-void loop() {
-  Serial.print("one reading:\t");
-  Serial.print(scale.get_units(), 1);
-  Serial.print("\t| average:\t");
-  Serial.println(scale.get_units(10), 1);
-
-  scale.power_down();			        // put the ADC in sleep mode
-  delay(5000);
-  scale.power_up();
-}


before we set the chopper config we need to know what it is

--- examples/TMC262MotorTester/Motor.ino
+++ examples/TMC262MotorTester/Motor.ino
@@ -4,10 +4,18 @@
 int sgFilter = 0;
 int direction = 1;

+char chopperMode = 0; //0 for spread, 1 for constant off
+char t_off = 2;
+char t_blank = 24;
+char fast_decay = 8;
+char wave_offset = 6;
+char comparator = 0;
+
+
 void startMotor() {
   Serial.println("Configuring stepper driver");
   //char constant_off_time, char blank_time, char hysteresis_start, char hysteresis_end, char hysteresis_decrement
-  tmc262Stepper.setSpreadCycleChopper(2,24,8,6,0);
+  tmc262Stepper.setSpreadCycleChopper(t_off,t_blank,fast_decay,wave_offset,comparator);
   tmc262Stepper.setRandomOffTime(0);

   tmc262Stepper.setMicrosteps(32);


Update pass through to work with Node

Update pass through to work with Node

--- examples/PassThrough/PassThrough.ino
+++ examples/PassThrough/PassThrough.ino
@@ -1,7 +1,7 @@
 /**
  * Use this sketch to talk directly to the LoRa module.
  *
- * In Serial Monitor, select "Both NL & CR" and "9600 baud" in
+ * In Serial Monitor, select "Both NL & CR" and "115200 baud" in
  * the bottom right dropdowns and send command a command like:
  *
  * mac get deveui
@@ -12,8 +12,12 @@
 #define debugSerial Serial

 void setup() {
+  while(!debugSerial || !loraSerial);
+
+  debugSerial.begin(115200);
+  delay(1000);
+
   loraSerial.begin(57600);
-  debugSerial.begin(9600);
 }

 void loop() {


Add I2C LCD 1602.

Add I2C LCD 1602.

--- monitor_client/monitor_client.ino
+++ monitor_client/monitor_client.ino
@@ -2,13 +2,28 @@
 #include <SoftwareSerial.h>
 #include <Wire.h>
 #include "Suli.h"
+
+//I2C Port expander and LCDs
+#include "LiquidCrystal_I2C.h"
+LiquidCrystal_I2C lcd(0x20, 16, 2);  // set the LCD address to 0x27 for a 16 chars and 2 line display
+//LCD address can be read in the program I2CScanner
+
+/*
+--- I2C Bus Scanner Test ---
+starting scanning of I2C bus from 1 to 127...
+
+addr: 32     HEX: 0x20   found!
+
+--- I2C Bus Scanner Complete ---
+
+*/

 //DHT11
 #include "DHT11.h"
 #define DHT11PIN 2
 dht11 DHT11;

-//DSM
+//DSM501A
 int pin = 3;
 unsigned long duration;
 unsigned long starttime;
@@ -21,14 +36,20 @@
 GPRS gprs(7, 8, 9600,"cmnet");
 char buffer[128];
 //Debug in PC
-bool is_debug = true;
+#define is_debug true

 void setup(){

     Serial.begin(9600);
-    //DSM init
+
+    //initialize DSM501A
     pinMode(3,INPUT);
     starttime = millis();
+
+    //initialize I2C LCD-1602
+    lcd.init();
+    lcd.backlight();
+    //initialize gprs
     if(!is_debug){
         gprs.init();
         // attempt DHCP
@@ -58,11 +79,6 @@
     {
         ratio = lowpulseoccupancy/(sampletime_ms*10.0);  // Integer percentage 0=>100
         concentration = 1.1*pow(ratio,3)-3.8*pow(ratio,2)+520*ratio+0.62; // using spec sheet curve
-        //Serial.print(lowpulseoccupancy);
-        // Serial.print(",");
-        Serial.print(ratio);
-        Serial.print(",");
-        //Serial.println(concentration);
         lowpulseoccupancy = 0;
         starttime = millis();

@@ -99,9 +115,22 @@
         //gprs.close();
         //gprs.disconnect();
     }else{
+        //Serial.print(lowpulseoccupancy);
+        // Serial.print(",");
+        Serial.print(ratio);
+        Serial.print(",");
+        //Serial.println(concentration);
         Serial.print((float)DHT11.temperature, 2);
         Serial.print(",");
         Serial.println((float)DHT11.humidity, 2);
+
+        lcd.clear();
+        //lcd.backlight();
+        lcd.print(ratio);
+        lcd.setCursor(8,0);
+        lcd.print((float)DHT11.temperature, 2);
+        lcd.setCursor(0,1);
+        lcd.print((float)DHT11.humidity, 2);
     }

     }


Extended rain statuses.

Extended rain statuses.

--- watertank.ino
+++ watertank.ino
@@ -73,7 +73,7 @@
 //------------------------------------------------------------------------
 // Water tank sensing and publishing to clouds (ThinkSpeak, Blynk)
 //-------------------------------------------------------------------------
-#define SKETCH "WATERTANK 1.3.0"
+#define SKETCH "WATERTANK 1.3.1"
 #include "credentials.h"

 const unsigned int TIMEOUT_WATCHDOG = 10000;  // Watchdog timeout in milliseconds
@@ -159,7 +159,7 @@
 // Statistical smoothing and exponential filtering
 const float FACTOR_RSSI  = 0.1;    // Smoothing factor for RSSI
 const float FACTOR_LIGHT = 0.2;    // Smoothing factor for light level
-const float FACTOR_RAIN  = 0.5;    // Smoothing factor for rain level
+const float FACTOR_RAIN  = 0.2;    // Smoothing factor for rain level
 const float FACTOR_WATER = 0.8;    // Smoothing factor for water level
 ExponentialFilter efRssi  = ExponentialFilter(FACTOR_RSSI);
 ExponentialFilter efLight = ExponentialFilter(FACTOR_LIGHT);
@@ -181,15 +181,17 @@
 const unsigned char LIGHT_STATUS_SUNNY    = 5;

 // Rain level
-const int RAIN_VALUE_DRY    = 63;
-const int RAIN_VALUE_DEW    = 127;
+const int RAIN_VALUE_DRY    = 64;
+const int RAIN_VALUE_DEW    = 128;
 const int RAIN_VALUE_RAIN   = 512;
+const int RAIN_VALUE_SHOWER = 1024;
 const int RAIN_VALUE_MARGIN = 4;         // Difference in value for status hysteresis
 //
 const unsigned char RAIN_STATUS_DRY    = 1;
 const unsigned char RAIN_STATUS_DEW    = 2;
 const unsigned char RAIN_STATUS_RAIN   = 3;
 const unsigned char RAIN_STATUS_SHOWER = 4;
+const unsigned char RAIN_STATUS_STORM  = 5;

 // Water level
 const int SONAR_DISTANCE_MAX = 95;          // Maximal valid measured distance (to tank bottom)
@@ -339,8 +341,10 @@
                     rainStatus = RAIN_STATUS_DEW;
                 } else if (rainValue <= RAIN_VALUE_RAIN) {
                     rainStatus = RAIN_STATUS_RAIN;
+                } else if (rainValue <= RAIN_VALUE_SHOWER) {
+                    rainStatus = RAIN_STATUS_SHOWER;
                 } else {
-                    rainStatus = RAIN_STATUS_SHOWER;
+                    rainStatus = RAIN_STATUS_STORM;
                 }
                 // Notify at status change
                 if (rainStatusOld != rainStatus && rainDiff >= RAIN_VALUE_MARGIN) {
@@ -358,6 +362,9 @@
                           break;
                         case RAIN_STATUS_SHOWER:
                           txtStatus = String("Heavy rain");
+                          break;
+                        case RAIN_STATUS_STORM:
+                          txtStatus = String("Rain storm");
                           break;
                     }
                     Blynk.notify(BLYNK_LABEL + txtStatus);


refactoring of the sample

refactoring of the sample

--- examples/client/client.ino
+++ examples/client/client.ino
@@ -1,18 +1,22 @@
 #include <SoftwareSerial.h>
 #include <esp8266_AT.h>

-int redPin = 11;
-int greenPin = 10;
-int bluePin = 9;
+//pin numbers of helper debug software serial
+#define rx_pin 2
+#define tx_pin 3

-SoftwareSerial mySerial(2, 3); // RX, TX
-Esp8266AT esp8266AT(&Serial, &mySerial);
+// replace value with access point name
+#define ap_name "write access point name here";
+
+// replace value with access point password
+#define ap_pass "write access point password here";
+
+
+SoftwareSerial debugSerial(rx_pin, tx_pin);
+Esp8266AT esp8266AT(&Serial, &debugSerial);

 void setup() {
-  pinMode(redPin, OUTPUT);
-  pinMode(greenPin, OUTPUT);
-  pinMode(bluePin, OUTPUT);
-
+
   // Open serial communications and wait for port to open:
   Serial.begin(115200);
   while (!Serial) {
@@ -21,20 +25,24 @@
   Serial.setTimeout(8000);

   // set the data rate for the SoftwareSerial port
-  mySerial.begin(115200);
-  mySerial.setTimeout(8000);
+  debugSerial.begin(115200);
+  debugSerial.setTimeout(8000);
 }

-int flag = 0;
+boolean connected = false;

 void loop() {
-    if (!esp8266AT.setup("nord", "asusn18urouter")) {
-        mySerial.println("Connection failed, please reset");
-        while (1);
+    if (!connected) {
+        if (!esp8266AT.setup(ap_name, ap_pass)) {
+            debugSerial.println("Connection failed, please reset");
+            while (1);
+        } else {
+            connected = true;
+        }
     }

     if (!esp8266AT.get("192.168.1.46", 1337, "GET / HTTP/1.0\r\nHost: localhost\r\n\r\n", "HTTP/1.1 200 OK")) {
-        mySerial.println("Last GET was failed");
+        debugSerial.println("Last GET was failed");
     }

    delay(5000);