Modified ESP_Programming/accel_tcp_post_01

--- ESP_Programming/accel_tcp_post_01/accel_tcp_post_01.ino
+++ ESP_Programming/accel_tcp_post_01/accel_tcp_post_01.ino
@@ -15,6 +15,8 @@

 #define USE_SERIAL Serial

+String row ="";
+
 const char* ssid     = "HackBulgaria";
 const char* password = "";

@@ -22,29 +24,31 @@
 const char* streamId   = "....................";
 const char* privateKey = "....................";

-float G[3]={0.0,0.0,0.0};
-float alpha=0.9;
+float G[3] = {0.0, 0.0, 0.0};
+float alpha = 0.9;

+long timer_read_from_accel = 0;
+long timer_send_data_wifi = 0;
 void setup() {
   Serial.begin(115200);
   delay(10);

- Serial.begin(9600);
-  Wire.begin(2,14);
-  accel.begin(BMA250_range_2g, BMA250_update_time_64ms);//This sets up the BMA250 accelerometer
-    USE_SERIAL.begin(115200);
-   // USE_SERIAL.setDebugOutput(true);
+  Serial.begin(9600);
+  Wire.begin(2, 14);
+  accel.begin(BMA250_range_2g, BMA250_update_time_4ms);//This sets up the BMA250 accelerometer
+  USE_SERIAL.begin(115200);
+  // USE_SERIAL.setDebugOutput(true);

-    USE_SERIAL.println();
-    USE_SERIAL.println();
-    USE_SERIAL.println();
+  //    USE_SERIAL.println();
+  //    USE_SERIAL.println();
+  //    USE_SERIAL.println();

-    for(uint8_t t = 4; t > 0; t--) {
-        USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
-        USE_SERIAL.flush();
-        delay(1000);
-    }
+  for (uint8_t t = 4; t > 0; t--) {
+    USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
+    USE_SERIAL.flush();
+    delay(1000);
+  }

   // We start by connecting to a WiFi network

@@ -52,31 +56,30 @@
   Serial.println();
   Serial.print("Connecting to ");
   Serial.println(ssid);
-
+
   WiFi.begin(ssid, password);
-
+
   while (WiFi.status() != WL_CONNECTED) {
     delay(500);
     Serial.print(".");
   }

   Serial.println("");
-  Serial.println("WiFi connected");
+  Serial.println("WiFi connected");
   Serial.println("IP address: ");
   Serial.println(WiFi.localIP());
 }

-int value = 0;
+//int value = 0;

 void loop() {
-  delay(5000);
-  ++value;
+//  delay(5000);
+//  ++value;

-  Serial.print("connecting to ");
-  Serial.println(host);
+//  Serial.print("connecting to ");
+//  Serial.println(host);

-  accel.read();//This function gets new data from the accelerometer
-
+
   // Use WiFiClient class to create TCP connections
   WiFiClient client;
   const int httpPort = 3001;
@@ -86,27 +89,33 @@
   }

-  G[0] = alpha * G[0] + (1-alpha) * accel.X;
-  G[1] = alpha * G[1] + (1-alpha) * accel.Y;
-  G[2] = alpha * G[2] + (1-alpha) * accel.Z;
-
+if (millis() - 20 >= timer_read_from_accel) {
+Serial.println(timer_read_from_accel);
+timer_read_from_accel = millis();
+  accel.read();//This function gets new data from the accelerometer
+
+  G[0] = alpha * G[0] + (1 - alpha) * accel.X;
+  G[1] = alpha * G[1] + (1 - alpha) * accel.Y;
+  G[2] = alpha * G[2] + (1 - alpha) * accel.Z;
+
   //char* row;
   //sprintf(row, "%d,%d,%d", accel.X - G[0], accel.Y - G[1], accel.Z - G[2]);
-
-  String row = String(int(accel.X - G[0])) + "," + String(int(accel.Y - G[1])) + "," + String(int(accel.Z - G[2]));
-  Serial.println(row);
-
-
+
+  row += String(int(accel.X - G[0])) + "," + String(int(accel.Y - G[1])) + "," + String(int(accel.Z - G[2]));
+  //  Serial.println(row);
+}
+
+Serial.println(row);
   // We now create a URI for the request
   String url = "/stream";
-  String tsData = String(accel.X);
+  String tsData = String(row);
   //Serial.println(tsData);
-
-  Serial.print("Requesting URL: ");
-  Serial.println(url);
+
+  //  Serial.print("Requesting URL: ");
+  //  Serial.println(url);

-
+
   // This will send the request to the server
   client.print(String("POST ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n");
   client.print("Content-Type: application/x-www-form-urlencoded\r\n");
@@ -115,16 +124,19 @@
   client.print("\r\n\r\n");
   client.print(tsData);
   client.print("Connection: close\r\n\r\n");
+
+if (millis() - 200 >= timer_send_data_wifi) {
+ timer_send_data_wifi = 0;

-  delay(1000);
-
+row = "";
   // Read all the lines of the reply from server and print them to Serial
-  while(client.available()){
-    String line = client.readStringUntil('\r');
-    Serial.print(line);
+  //  while(client.available()){
+  //    String line = client.readStringUntil('\r');
+  //    Serial.print(line);
+  //  }
+
+  //  Serial.println();
+  //  Serial.println("closing connection");
   }
-
-  Serial.println();
-  Serial.println("closing connection");
 }


Remove unused function

Remove unused function

--- ins-node/src/wifi_module/wifi_module.ino
+++ ins-node/src/wifi_module/wifi_module.ino
@@ -13,17 +13,6 @@

 const uint8_t TX_PIN = 10;
 const uint8_t RX_PIN = 9;
-
-/**
-   Establishes a connection with the predefined server
-   @return  true for succesfull connection
-            false for failed connection
-*/
-bool connectToServer() {
-  WiFiClient client;
-  const int SERVER_PORT = 8050;
-  return client.connect(SERVER_IP, SERVER_PORT);
-}

 /**
    Gets the network context (i.e. MAC address and RSSI value) of the specified


Flicking back to blinking once per second.

--- firmware.ino
+++ firmware.ino
@@ -6,7 +6,7 @@

 void loop() {
     digitalWrite(ledPin, LOW);
-    delay(50);
+    delay(1000);
     digitalWrite(ledPin, HIGH);
-    delay(50);
-}+    delay(1000);
+}


new blah 2

new blah 2

--- proj/hypercube/HCS/HCS.ino
+++ proj/hypercube/HCS/HCS.ino
@@ -203,7 +203,7 @@
   // Handle switching between outer shell animations. Don't do this if we're
   // already switching the inner shell though, don't want to figure that out
   EVERY_N_SECONDS(10) {
-    oAnimCounter = (oAnimCounter + 1) % numAnimation;
+    oAnimCounter = (oAnimCounter + 1) % 3;
   }

   // Same deal for the inner shell
@@ -272,15 +272,15 @@
       }
       chase_spiral(OUTER, oOffset, true);
       break;
-    case 3:
-      chase_mod(OUTER, true);
-      break;
-    case 4:
-      snow_anim(OUTER, 50, 0.3);
-      break;
-    case 5:
-      fill_shell(OUTER);
-      break;
+    //case 3:
+    //  chase_mod(OUTER, true);
+    //  break;
+    //case 4:
+    //  snow_anim(OUTER, 50, 0.3);
+    //  break;
+    //case 5:
+    //  fill_shell(OUTER);
+    //  break;
   }

   // Merge each shell to the whole LED array and push to the lights


added MODE define

added MODE define

--- firmware/examples/FastLedComparison/FastLedComparison.ino
+++ firmware/examples/FastLedComparison/FastLedComparison.ino
@@ -1,15 +1,30 @@
-#define SMARTMATRIX_ENABLED   1
+/*
+  Demo intended to compare APA102 refreshing using Temporal Dithering, no Dithering, and SmartMatrix with Dynamic Global Brightness Control
+  Set MODE and BRIGHTNESS defines at the top to reproduce the results in the demo video (MODE_SMARTMATRIX_COLORCORRECTION wasn't used in the video)
+
+  Connect APA102 Data Pin to D2
+  Connect APA102 Clock Pin to D4
+*/
+
+#define MODE_SMARTMATRIX_NOCOLORCORRECTION   0
+#define MODE_SMARTMATRIX_COLORCORRECTION     1
+#define MODE_FASTLED_DITHERING               2
+#define MODE_FASTLED_NODITHERING             3
+
+// SET SKETCH OPTIONS HERE:
+#define MODE MODE_SMARTMATRIX_NOCOLORCORRECTION
+#define BRIGHTNESS 255

 #include "application.h"

-#if (SMARTMATRIX_ENABLED == 1)
+#if (MODE == MODE_SMARTMATRIX_NOCOLORCORRECTION || MODE == MODE_SMARTMATRIX_COLORCORRECTION)
   #include "SmartMatrix3/SmartMatrix3.h"
 #endif

 #include "FastLEDSmartMatrix/FastLEDSmartMatrix.h"
 FASTLED_USING_NAMESPACE;

-#if (SMARTMATRIX_ENABLED == 1)
+#if (MODE == MODE_SMARTMATRIX_NOCOLORCORRECTION || MODE == MODE_SMARTMATRIX_COLORCORRECTION)
   #define COLOR_DEPTH 24                  // known working: 24, 48 - If the sketch uses type `rgb24` directly, COLOR_DEPTH must be 24
   const uint8_t kMatrixWidth = 16;        // known working: 16, 32, 48, 64
   const uint8_t kMatrixHeight = 16;       // known working: 32, 64, 96, 128
@@ -46,7 +61,7 @@

 const uint8_t scale = 256 / kMatrixWidth;

-#if (SMARTMATRIX_ENABLED == 1)
+#if (MODE == MODE_SMARTMATRIX_NOCOLORCORRECTION || MODE == MODE_SMARTMATRIX_COLORCORRECTION)
   uint16_t XY(uint8_t x, uint8_t y) {
     return kMatrixWidth * y + x;
   }
@@ -68,7 +83,7 @@
   }
 #endif

-#if (SMARTMATRIX_ENABLED == 1)
+#if (MODE == MODE_SMARTMATRIX_NOCOLORCORRECTION || MODE == MODE_SMARTMATRIX_COLORCORRECTION)
   // scale the brightness of all pixels down
   void dimAll(byte value)
   {
@@ -88,10 +103,8 @@
   }
 #endif

-#define BRIGHTNESS 255
-
 void setup() {
-#if (SMARTMATRIX_ENABLED == 1)
+#if (MODE == MODE_SMARTMATRIX_NOCOLORCORRECTION || MODE == MODE_SMARTMATRIX_COLORCORRECTION)
   matrix.addLayer(&backgroundLayer);
   matrix.addLayer(&scrollingLayer);
   matrix.begin();
@@ -101,15 +114,22 @@
   FastLED.addLeds<CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER, DATA_RATE_MHZ(1)>(leds, NUM_LEDS).setCorrection(TypicalSMD5050);
   FastLED.setBrightness( BRIGHTNESS );

-  FastLED.setDither(BINARY_DITHER);
-  //FastLED.setDither(DISABLE_DITHER);
+  #if (MODE == MODE_FASTLED_DITHERING)
+    FastLED.setDither(BINARY_DITHER);
+  #else
+    FastLED.setDither(DISABLE_DITHER);
+  #endif
+
+  FastLED.show();
 #endif
+
+  delay(2000);
 }

 void loop() {
   EVERY_N_MILLISECONDS(1000/30) {

-#if (SMARTMATRIX_ENABLED == 1)
+#if (MODE == MODE_SMARTMATRIX_NOCOLORCORRECTION || MODE == MODE_SMARTMATRIX_COLORCORRECTION)
     buffer = backgroundLayer.backBuffer();
 #endif

@@ -120,7 +140,7 @@

     for (uint8_t x = 0; x < kMatrixWidth; x++) {
       uint8_t y = quadwave8(x * 2 + theta) / scale;
-#if (SMARTMATRIX_ENABLED == 1)
+#if (MODE == MODE_SMARTMATRIX_NOCOLORCORRECTION || MODE == MODE_SMARTMATRIX_COLORCORRECTION)
       buffer[XY(x, y)] = CRGB(CHSV(x + hue, 255, 255));
 #else
       leds[XY(x, y)] = CHSV(x + hue, 255, 255);
@@ -130,12 +150,15 @@
     theta++;
     hue++;

-#if (SMARTMATRIX_ENABLED == 1)
+#if (MODE == MODE_SMARTMATRIX_NOCOLORCORRECTION || MODE == MODE_SMARTMATRIX_COLORCORRECTION)
     backgroundLayer.swapBuffers(true);
+#else
+    FastLED.show();
 #endif
   }

-#if (SMARTMATRIX_ENABLED == 0)
+#if (MODE == MODE_FASTLED_DITHERING)
+  // FastLED needs to update LEDs during idle time to do dithering
   FastLED.show();
 #endif
 }


Delete Main_draft_11.ino

Delete Main_draft_11.ino

--- Main_draft_11.ino
+++ Main_draft_11.ino
@@ -1,295 +0,0 @@
-
-//**************************************************************//
-//  Name    : LAGERLOGGER! (With IC2 display)
-//  Author  : Paul Jarvey
-//  Date    : 5 Oct, 2013
-//  Modified: 17 Jan, 2017
-//  Version : BETA 0.8
-//  Notes   : 20x4 lc2 display, DHT22 temp/hum mon,
-//          : control via rotary encoder, and 4 output controls
-//          : note to self - control backlight with   lcd.setBacklight(1)
-//          : screen connected  : SDA >> A4 , SCL >> A5
-//****************************************************************
-
-//redefine how compiler understands "B_SIG", "A_SIg"
-unsigned int pulses = 0, A_SIG=0, B_SIG=1;
-int pulseAdjust = 4;
-
-// Call libraries for display, sensor, I2C, and memory. Library setup included as well.
-#include <avr/pgmspace.h>
-char buffer[20];
-
-#include <OneWire.h>
-#include <Wire.h>
-#include <LiquidCrystal_I2C.h>
-LiquidCrystal_I2C lcd(0x27,20,4);
-#include <DHT.h>
-#include <EEPROM.h>
-#include "EEPROMAnything.h"
-
-
-// Special Characters for the display and display animations
-#if defined(ARDUINO) && ARDUINO >= 100
-#define printByte(args)  write(args);
-#else
-#define printByte(args)  print(args,BYTE);
-#endif
-
-uint8_t heart[8] = { 0x0,0xa,0x1f,0x1f,0xe,0x4,0x0};
-uint8_t deg[8] = { 0x1c,0x14,0x1c,0x0,0x3,0x4,0x4,0x3};
-uint8_t hum[8] = { 0x12,0x4,0x9,0x0,0x4,0x7,0x5,0x5};
-uint8_t up1[8] = { 0x10,0x14,0x2,0x10,0x0,0x2,0x10,0x0};
-uint8_t up2[8] = { 0x0,0x2,0x10,0x0,0x2,0x10,0xa,0x0};
-uint8_t up3[8] = { 0x2,0x10,0x0,0x2,0x10,0x0,0x2,0x10};
-uint8_t Pv[8] = { 0x1c,0x14,0x1c,0x10,0x10,0x5,0x5,0x2};
-uint8_t Sv[8] = { 0xc,0x10,0x8,0x4,0x18,0x5,0x5,0x2};
-// end special chars
-
-// Sensor pins:
-#define DHTPIN 4
-#define DHTTYPE DHT22
-DHT dht(DHTPIN, DHTTYPE);
-
-//user i/o pins
-const int buttonPin = 11;    // the pin that the pushbutton is attached to
-const int ledPin = 13;       // the pin that the LED is attached to (for status)
-
-
-
-//************* Begin Libraries Setup ***************//
-
-const char* OnOff[3] = {
-"ON  ",
-"OFF ",
-"AUTO"};
-
-const char* YesNo[2] = {
-"Yes",
-"No "};
-
-
-const char* mainMenu[9] = {
-"Exit            ",
-"Program sequence",
-"Set temp/hum    ",
-"Options & PID",
-"Fan timer    ",
-"Light timer     ",
-"View sensor data",
-"Brew/grow mode  ",
-"Save settings "};
-
-
-
-
-//************* Begin Variables Setup ***************//
-
-//Sensors (ds18s20 needs additional chatter)
-int DS18S20_Pin = 5; //DS18S20 Signal pin on digital 2
-  byte addr1[8]= {0x28, 0x48, 0xAE, 0x3C, 0x05, 0x00, 0x00, 0x34};
-  byte addr2[8]= {0x28, 0xC7, 0xCD, 0x4C, 0x05, 0x00, 0x00, 0x0D};
-  byte data1[12];
-  byte data2[12];
-  byte MSB = 0;
-  byte LSB = 0;
-  float tempRead = 0;
-  float TemperatureSum = 0;
-  OneWire ds(DS18S20_Pin);
-
-//controller outputs
-int ControlCpin = 9; // control to fridge
-int ControlTpin = 7; // control to temperature/heater  (get aquarium heater)
-int ControlHpin = 8; // control to humidifier
-int ControlLpin = 6; // control to light
-int ControlApin = 10; // control to airflow
-
-//operational vars (the button)
-//int buttonPushCounter = 0;   // counter for the number of button presses DEPRACATED
-int buttonState = 0;         // current state of the button
-int lastButtonState = 0;     // previous state of the button
-boolean buttonstate = false; // calculastate of the button (includes timer delay. use this in menus)
-int buttontime = 0;          // press length measure
-int buttontimeon = 0;        // necessary for press length measure
-
-//operational vars (the rotary)
-int pulseMod = 0;            // modulus to reduce scroll speed
-int pulseprev = 0;         // to measure change in rotary position
-int pulselast = 0;         // backlight onoff
-//operational vars (the menus and presets)
-byte menu = 0;               // defines current screen (used in cases in main loop)
-byte submenu = 0;            // defines submenu screen (used in cases in main loop)
-byte Mode = 0;               // define mode: brew = 0, myc = 1 COULD JUST USE MENU
-//byte preset = 0;             // Active Preset (grow and brew)
-int selector = 0;            // could change to byte
-int selectorprev = 0;        // Must be int. Maybe long. Defines the next menu position by changing pulses
-
-//operational vars (sensors and timing)
-unsigned int sensorInterval = 5000;         // time between readings
-unsigned long int sensorTime = 0;           // current time
-unsigned long int sensorTime2 = 0;          // time of last sensor reading
-unsigned long int backlighton = 0;
-unsigned long int backlighttime = 120000;
-
-
-
-
-// fans, lights, and timers
-byte FanAuto = 0;
-unsigned long int fanONmillis = 0;
-unsigned long int fanOFFmillis = 0;
-byte fanON = 0;
-byte fanOFF = 0;
-boolean fanstate = false;
-unsigned long int Time = 0;
-unsigned long int TimeAdjust = 0;
-int brewtimer = 0;
-double brewtimerRef = 0;
-byte brewtimerON = 0;
-float brewtimerSv = 20;
-unsigned long int LightON = 0;
-unsigned long int LightOFF = 0;
-unsigned int Hours = 0;
-unsigned int Minutes = 0;
-unsigned int Seconds = 0;
-byte daysAdj = 0; //not implemented yet
-
-//key var storage
-float PvH = 0;
-double PvT = 0;
-float SvH = 0;
-double SvT = 0;
-
-
-
-//Reading averaging
-//const int numReadings = 4;   // number of readings to average (rolling average) ALSO changes loading screen length (as values are populated twice per second)
-//float readingsT[numReadings];// Temp readings to average
-//float readingsH[numReadings];// Hum readings to average
-
-//byte readingsCount = 0;
-//byte index = 0;               // index of the current reading
-//byte index2 = 0;
-//float totalT = 0;            // current Temp total
-//float totalH = 0;            // current Hum total
-//float totalIT = 0;            // current Temp total
-//fafloat totalIH = 0;
-
-float Temp1;                   //Current readings
-float Temp2;                   //Current readings
-float Temp3;                   //Current readings
-float Hum;
-int Day = 0;                //Current day in program (for calcs)
-int DayPrev = 0;            //Previous day for counting and eeprom NOT SET UP YET
-
-
-
-// Fridge limits
-int dutyCycle = 2; // in minutes
-int minCool = 10; // in minutes
-byte coolON = 0;  // PID attached to this
-
-// Heat limits
-byte heatON = 0;  // PID attached to this
-
-//PID  variables
-#include <PID_v1.h>
-byte autotune = 0;
-
-//cool
-double Kp = 8;
-double Ki = 2;
-double Kd = 2;
-double Output;
-PID coolPID(&PvT, &Output, &SvT ,Kp,Ki,Kd, REVERSE);
-double coolWindowSize = 1800000;  //  60k = 1min
-unsigned long coolWindowStartTime;
-unsigned long coolOffElapsed = 0;
-
-//heat
-double Outputh;
-PID heatPID(&PvT, &Outputh, &SvT ,4,0.8,0.8, DIRECT);
-double heatWindowSize = 600000;  // 60k = 1min
-unsigned long heatWindowStartTime;
-unsigned long heatOffElapsed = 0;
-
-
-
-// ensure setpoint, input, and outpit are defined
-
-//************* End Variables Setup ***************//
-
-
-void setup(){
-
-//Sensor start
-  dht.begin();
-
-//Interrupts initialize
-  attachInterrupt(0, A_RISE, RISING);
-  attachInterrupt(1, B_RISE, RISING);
-  pinMode(buttonPin, INPUT); // initialize momentary button input
-
-//Pin declarations
-  pinMode(ControlTpin, OUTPUT); //set outputs
-  pinMode(ControlHpin, OUTPUT);
-  pinMode(ControlLpin, OUTPUT);
-  pinMode(ControlApin, OUTPUT);
-  pinMode(ControlCpin, OUTPUT);
-  digitalWrite(ControlTpin, HIGH); // write outputs HIGH (off in this case) FIRST to prevent startup jitters.
-  digitalWrite(ControlHpin, HIGH);
-  digitalWrite(ControlLpin, HIGH);
-  digitalWrite(ControlApin, HIGH);
-  digitalWrite(ControlCpin, HIGH);
-
-//LCD and special chars
-  Serial.begin(115200);
-  lcd.init();
-  lcd.backlight();
-  lcd.createChar(0, heart);
-  lcd.createChar(1, deg);
-  lcd.createChar(2, hum);
-  lcd.createChar(3, up1);
-  lcd.createChar(4, up2);
-  lcd.createChar(5, up3);
-  lcd.createChar(6, Pv);
-  lcd.createChar(7, Sv);
-  lcd.clear();
-  LoadScreen();
-
-// load all the saved values from EEPROM
-  EEPROM_recall();
-
-  //fanONmillis = 0;
-  fanOFFmillis = millis();
-  HomeSetup();
-
-  //PID shit
-  //coolWindowSize = dutyCycle * 60000;
-  coolPID.SetOutputLimits(0, coolWindowSize/1000);
-  coolPID.SetMode(AUTOMATIC);
-  coolOffElapsed = millis();
-  heatPID.SetOutputLimits(0, heatWindowSize/1000);
-  heatPID.SetMode(AUTOMATIC);
-  coolOffElapsed = millis();
-}
-
-
-void loop(){
-
-  Button();
-  Menus ();
-
-  /* //TESTING OUTPUT (enable this line to print interrupt data to the serial port
-  Serial.print(pulses);
-  Serial.print(" : ");
-  Serial.println(pulseMod);*/
-
-
-}
-
-
-
-
-
-
-


Change timing for nicer view

Change timing for nicer view

--- chessclock/chessclock.ino
+++ chessclock/chessclock.ino
@@ -40,7 +40,7 @@
         setDisplay(row, *maintext);                        // haal de te tonen data op.
         digitalWrite(strobePin, HIGH);                     // update de shiftregisters.
         digitalWrite (resredPin, HIGH);                    // en zet display terug aan.
-        delayMicroseconds(2000);                           // pauseren want de update gaat te vlug.
+        delayMicroseconds(1000);                           // pauseren want de update gaat te vlug.
     }
 }
 void setRow (int row)                                  // deze functie kan gebruikt worden voor het multiplexen van de zeven rijen.
@@ -107,4 +107,4 @@
         SPI.transfer(outputbytes[i]);
     };

-}
+}


Clean up publish Temp methods

Clean up publish Temp methods

--- temperature-relay.ino
+++ temperature-relay.ino
@@ -137,30 +137,12 @@
   }
 }

-void publishTemp(float temp) {
+void publishTemp(const char pLabel[], const char sLabel[], float temp) {
   char publishString[20];

   snprintf(publishString, 20,"%.4f", temp);
-  Particle.publish("temperature", publishString);
-  Serial.print("Temp: ");
-  Serial.println(publishString);
-}
-
-void publishAverage(float temp) {
-  char publishString[20];
-
-  snprintf(publishString, 20,"%.4f", temp);
-  Particle.publish("minute_average", publishString);
-  Serial.print("Average: ");
-  Serial.println(publishString);
-}
-
-void publishOutdoor(float temp) {
-  char publishString[20];
-
-  snprintf(publishString, 20,"%.4f", temp);
-  Particle.publish("outdoor_temp", publishString);
-  Serial.print("Outdoor: ");
+  Particle.publish(pLabel, publishString);
+  Serial.print(sLabel);
   Serial.println(publishString);
 }

@@ -209,7 +191,7 @@

   if (tempStr != NULL) {
     outdoorTemp = tempStr.toFloat();
-    publishOutdoor(outdoorTemp);
+    publishTemp("outdoor_temp", "Outdoor Temp: ", outdoorTemp);
   }
 }

@@ -248,8 +230,8 @@
       Serial.print("Average Temp: ");
       Serial.println(minuteAverage);

-      publishAverage(minuteAverage);
-      publishTemp(temperature);
+      publishTemp("minute_average", "Average Temp: ", minuteAverage);
+      publishTemp("temperature", "Temp: ", temperature);
     } else {
       Serial.println("No Sensors to Read");
     }


Calc speed in kph

Calc speed in kph

--- ScooterSpeedo.ino
+++ ScooterSpeedo.ino
@@ -17,10 +17,16 @@
 #include <Adafruit_MMA8451.h>
 #include <Adafruit_Sensor.h>

+// Scooter constants
+const float WHEEL_RADIUS = 6.0; // in cm
+const float WHEEL_CIRCUMFERENCE = 2 * WHEEL_RADIUS * PI;
+double kph = 0.0;
+
 // Hall effect sensor read pin, make it an interrupt pin so we catch all revolutions
 const byte HALL_SENSOR = 2;
 boolean isHallSensorTriggered = false;
 int tickCount = 0;
+int currentMillis = 0;
 int millisSinceLastTick = 0;

 // 16x2 LCD display pins
@@ -40,6 +46,9 @@
 Adafruit_MMA8451 mma = Adafruit_MMA8451();

 void setup() {
+  Serial.begin(115200);
+  Serial.println(WHEEL_CIRCUMFERENCE);
+
   pinMode(HALL_SENSOR, INPUT_PULLUP);
   attachInterrupt(0,triggerCount, FALLING);

@@ -70,15 +79,18 @@
   mma.getEvent(&event);

   lcd.clear();
-
-  lcd.print("Revolutions: ");

-  lcd.print(tickCount);
+  kph = calculateKPH();
+
+  lcd.print("Spd: ");
+  lcd.print(kph);
+  lcd.print("kph");

   lcd.setCursor(0,1);
   lcd.print("AccY:");
   lcd.print(event.acceleration.y);
   lcd.print(" m/s^2");
+
   // using blocking delay debounces the accelerometer and gives the display time to refresh
   delay(250);
 }
@@ -89,3 +101,13 @@
   millisSinceLastTick = millis();
 }

+// ******************* INTERRUPT EVENTS *******************
+
+double calculateKPH() {
+  // How many CM per second we've traveled, based on wheel circumference and number of wheel turns since last check
+  double cmps =  (1000/(millisSinceLastTick - currentMillis)) * WHEEL_CIRCUMFERENCE * tickCount;
+  // reset counts
+  tickCount = 0;
+  currentMillis = millisSinceLastTick;
+  return cmps/10000 *360;
+}


Update ir_receiver_array_demo.ino

Update ir_receiver_array_demo.ino

--- demos/ir_receiver_array_demo/ir_receiver_array_demo.ino
+++ demos/ir_receiver_array_demo/ir_receiver_array_demo.ino
@@ -16,10 +16,10 @@
 }
 //loop repeats continuously
 void loop(){
-  //declare array for holding IR receiver digital readings
+
   boolean ir_receiver_readings[7];

-  //fill the array
+  // Read each sensor
   ir_receiver_readings[0] = digitalRead(2);
   ir_receiver_readings[1] = digitalRead(3);
   ir_receiver_readings[2] = digitalRead(4);
@@ -28,7 +28,7 @@
   ir_receiver_readings[5] = digitalRead(7);
   ir_receiver_readings[6] = digitalRead(8);

-  //loop through the IR readings
+  // Print the sensor readings
   for(int i=0;i<7;i++){
     //print 1 to serial if beacon is detected
     if (ir_receiver_readings[i] == 0)
@@ -36,8 +36,6 @@
     else
       Serial.print("0 ");
   }
-
-  //print newline character
   Serial.print("\n");

   //Wait 30ms


Changed Job editor behaviour

Changed Job editor behaviour

Now autosaves on start/end time change


Integral-only control.

Integral-only control.

--- temp_ctrl/temp_ctrl.ino
+++ temp_ctrl/temp_ctrl.ino
@@ -22,20 +22,20 @@

 #define SAMPLE_DELAY_MS 400L
 #define HEATER_PERIOD_MS 10000L
-#define PID_UPDATE_PERIOD_MS 125L
+#define PID_UPDATE_PERIOD_MS SAMPLE_DELAY_MS + 33L

 //#define OPEN_LOOP_MODE
 #define PID_MODE

 #	define DUTY_INIT 0.0

-#define PGAIN 5
-#define IGAIN 0
+#define PGAIN 0
+#define IGAIN 0.001
 #define DGAIN 0
 #define IMIN 0
 #define IMAX 10000

-#define TARGET 23.5 // ~20.5C ambient + 23.5C rise = 44C target
+#define TARGET 23.5 // ~20.5C ambient + 23.5C rise = 44C'ish

 #define TEMP_TO_DUTY_SLOPE 0.1
 #define TEMP_TO_DUTY_OFFSET 0.0


corrigido bloqueioPorAlarme, gera um resetCompleto em caso de alarme

--- EMP-B-Due.ino
+++ EMP-B-Due.ino
@@ -248,7 +248,7 @@
   alarme_ativo = VERDADEIRO;
   stand_by = FALSO;
   escreveSerial("\n<< Alarme! >>\n");
-  reiniciaSaidas();
+  resetCompleto();
   escreveSerial(texto + " detectou uma falha!");
 }

@@ -467,7 +467,6 @@
   maquina_ligada = FALSO;
   dosador_ligado = FALSO;
   datador_ligado = FALSO;
-  alarme_ativo = FALSO;
   fotocelula_liberada = FALSO;
   fotocelula_cortou = FALSO;
   produzindo = FALSO;


bring the energino ethernet code in sync with the yun

--- sketches/EnerginoEthernet/EnerginoEthernet.ino
+++ sketches/EnerginoEthernet/EnerginoEthernet.ino
@@ -21,14 +21,14 @@
  *  #D<integer>, sets the sensitivity in mV of the current sensor [default is 185]
  *  #R, resest the configuration to the defaults
  *  #F<feed>, sets the feed id [default is 0]
- *  #K<key>, sets the COSM authentication key [default is -]
+ *  #K<key>, sets the COSM authentication key [default is foo]
  *  #H, sets the remote host ip address [default is 216.52.233.121 (Cosm)]
  *  #O, sets the remote host port [default is 80]
  *
  * No updates are sent over the Ethernet interface if the feed id is set to 0
  *
  * Serial putput:
- *   #Energino,0,<voltage>,<current>,<power>,<relay>,<period>,<samples>,<ip>,<port>,<host>,<port>,<feed>,<key>
+ *   #Energino,0,<voltage>,<current>,<power>,<relay>,<period>,<samples>,<feed>,<url>,<key>
  *
  * RESTful interface:
  *  This sketch accepts HTTP requests in the form GET /<cmd>/<param>/[value], where "cmd"
@@ -49,29 +49,16 @@
  */

 #include <SPI.h>
-#include <SD.h>
 #include <Ethernet.h>
 #include <EEPROM.h>
 #include <avr/eeprom.h>

-// comment/uncomment to disable/enable debug
-//#define DEBUG
-
-// comment/uncomment to disable/enable ethernet support
-#define NOETH
-
-#define RELAY_PIN 2
-
-#ifdef DEBUG
-#define DBG if(1)
-#else
-#define DBG if(0)
-#endif
-
-// Feed id
-long FEED = 0;
-// Cosm key
-char KEY[] = "-";
+#define APIKEY        "foo"                               // replace your Xively api key here
+#define FEEDID        0                                   // replace your feed ID
+
+#define RELAYPIN      2
+#define CURRENTPIN    A0
+#define VOLTAGEPIN    A1

 // Energino parameters
 int R1 = 100;
@@ -88,35 +75,24 @@
 float VFinal = 0.0;
 float IFinal = 0.0;

-#ifndef NOETH
-
-// Cosm configuration
+// Xively configuration
 IPAddress HOST(216,52,233,121);
 long PORT = 80;

 // Server configuration parameters, energino will listen for
 // incoming requests on this port
-const long SERVER_PORT = 8180;
-
-// HTML response
-const char HTML_RESPONSE[43] PROGMEM = "HTTP/1.1 200 OK\nContent-Type: text/html\n\n";
-const char HTML_RESPONSE_404[25] PROGMEM = "HTTP/1.1 404 Not Found\n\n";
-
-// JSON response header and footer
-const char JSON_RESPONSE[49] PROGMEM = "HTTP/1.1 200 OK\nContent-Type: application/json\n\n";
+const long SERVER_PORT = 80;

 // working vars
 EthernetServer server(SERVER_PORT);

-#endif
-
 // magic string
-const char MAGIC[] = "Energino";
+const char MAGIC[] = "EnerginoEthernet";
 const int REVISION = 1;

 // Permanent configuration
 struct settings_t {
-  char magic[9];
+  char magic[17];
   long period;
   int r1;
   int r2;
@@ -124,7 +100,7 @@
   int sensitivity;
   byte mac[6];
   char apikey[49];
-  long feed;
+  long feedid;
   IPAddress host;
   long port;
 }
@@ -137,11 +113,10 @@
   settings.r2 = R2;
   settings.offset = OFFSET;
   settings.sensitivity = SENSITIVITY;
-#ifndef NOETH
-  settings.feed = FEED;
+  settings.feedid = FEEDID;
   settings.host = HOST;
   settings.port = PORT;
-  strcpy (settings.apikey,KEY);
+  strcpy (settings.apikey,APIKEY);
   settings.mac[0] = 0x90;
   settings.mac[1] = 0xA2;
   settings.mac[2] = 0xDA;
@@ -149,15 +124,14 @@
     randomSeed(analogRead(0));
     settings.mac[i] = random(0, 255);
   }
-#endif
 }

 void setup() {
   // Set serial port
   Serial.begin(115200);
   // Default on
-  pinMode(RELAY_PIN,OUTPUT);
-  digitalWrite(RELAY_PIN, LOW);
+  pinMode(RELAYPIN,OUTPUT);
+  digitalWrite(RELAYPIN, LOW);
   // Loading setting
   eeprom_read_block((void*)&settings, (void*)0, sizeof(settings));
   if (strcmp(settings.magic, MAGIC) != 0) {
@@ -166,34 +140,25 @@
   }
   // set sleep counter
   resetSleep(settings.period);
-#ifndef NOETH
   // Try to configure the ethernet using DHCP
-  Serial.println("@dhcp");
+  Serial.print("@dhcp... ");
   if (Ethernet.begin(settings.mac) == 0) {
-    Serial.println("@dhcp: fail");
+    Serial.println("fail");
     return;
   }
-  Serial.println("@dhcp done");
+  Serial.println("done");
   // Start server
   server.begin();
-  // Init SD
-  pinMode(10, OUTPUT);
-  // see if the card is present and can be initialized:
-  if (!SD.begin(4)) {
-    Serial.println("@sd: fail");
-    return;
-  }
-#endif
 }

 void loop() {

   // Make sure that update period is not too high
-#ifndef NOETH
-  if ((settings.feed != 0) && (settings.period < 2000)) {
-    resetSleep(2000);
-  }
-#endif
+  // when pushing data to Xively (one sample every
+  // 5 seconds should be a reasonable lower boud)
+  if ((settings.feedid != 0) && (settings.period < 5000)) {
+    resetSleep(5000);
+  }

   // Start profiling
   long started = millis();
@@ -202,9 +167,7 @@
   serParseCommand();

   // Listen for incoming requests
-#ifndef NOETH
   handleRequests();
-#endif

   // Instant values are too floating,
   // let's smooth them up
@@ -221,9 +184,7 @@
   IFinal = scaleCurrent((float)IRaw/sleep);

   // send data to remote host
-#ifndef NOETH
   sendData();
-#endif

   // dump to serial
   dumpToSerial();
@@ -249,7 +210,7 @@
   char cmd = '\0';
   int i, serAva;
   char inputBytes[60] = {
-    '\0'           };
+    '\0'               };
   char * inputBytesPtr = &inputBytes[0];
   // read command from serial
   serAva = Serial.available();
@@ -276,11 +237,10 @@
   if (cmd == 'R') {
     reset();
   }
-#ifndef NOETH
   else if (cmd == 'F') {
     long value = atol(inputBytesPtr);
     if (value >= 0) {
-      settings.feed = value;
+      settings.feedid = value;
     }
   }
   else if (cmd == 'K') {
@@ -302,7 +262,6 @@
       settings.port = value;
     }
   }
-#endif
   else {
     int value = atoi(inputBytesPtr);
     if (value < 0) {
@@ -325,162 +284,157 @@
     }
     else if (cmd == 'S') {
       if (value > 0) {
-        digitalWrite(RELAY_PIN, HIGH);
+        digitalWrite(RELAYPIN, HIGH);
       }
       else {
-        digitalWrite(RELAY_PIN, LOW);
+        digitalWrite(RELAYPIN, LOW);
       }
     }
   }
   eeprom_write_block((const void*)&settings, (void*)0, sizeof(settings));
 }
-
-#ifndef NOETH

 // This method accepts HTTP requests in the form GET /<cmd>/<param>/[value]
 void handleRequests() {
+
   EthernetClient request = server.available();
+
   if (request) {
-    int idx = 0;
-    char buffer[50];
-    while (request.connected() && request.available()) {
-      // Read char by char HTTP request
-      char c = request.read();
-      DBG Serial.print(c);
-      // Store characters to string
-      if (idx < 50) {
-        buffer[idx] = c;
-      }
-      idx++;
-      // 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 >= 50) {
-        char * method;
-        method = strtok (buffer, " ");
-        if (strcmp(method, "GET") == 0) {
-          char * toks;
-          toks = strtok (NULL," ");
-          toks = strtok (toks,"/");
-          if (strcmp(toks, "read") == 0) {
-            toks = strtok (NULL, "/");
-            if (strcmp(toks, "datastreams") == 0) {
-              writeHeader(request, JSON_RESPONSE);
-              writeDataStream(request);
-              break;
-            }
-            else if (strcmp(toks, "switch") == 0) {
-              writeHeader(request, JSON_RESPONSE);
-              request.print("[");
-              request.print(digitalRead(RELAY_PIN));
-              request.print("]\n");
-              break;
-            }
-          }
-          else if (strcmp(toks, "write") == 0) {
-            toks = strtok (NULL, "/");
-            if (strcmp(toks, "switch") == 0) {
-              toks = strtok (NULL, "/");
-              if (atoi(toks) > 0) {
-                digitalWrite(RELAY_PIN, HIGH);
-              }
-              else {
-                digitalWrite(RELAY_PIN, LOW);
-              }
-              writeHeader(request, JSON_RESPONSE);
-              request.print("[");
-              request.print(digitalRead(RELAY_PIN));
-              request.print("]\n");
-              break;
-            }
-          }
-          else {
-            File dataFile = SD.open(toks, FILE_READ);
-            if (dataFile) {
-              writeHeader(request, HTML_RESPONSE);
-              while (dataFile.available()) {
-                request.write(dataFile.read());
-              }
-              dataFile.close();
-              request.write("\n");
-              break;
-            }
-          }
-        }
-        writeHeader(request, HTML_RESPONSE_404);
-        request.write("\n");
-        break;
-      }
-    }
-    // give the web browser time to receive the data
-    delay(10);
-    // close the connection:
+
+    String method = request.readStringUntil('/');
+    method.trim();
+
+    if (method != "GET") {
+      request.print(F("HTTP/1.1 501 Not Implemented\n\n"));
+      request.stop();
+      return;
+    }
+
+    String url = request.readStringUntil(' ');
+    url.trim();
+
+    if (url.startsWith("arduino/datastreams")) {
+
+      String command = url.substring(20, -1);
+
+      if (command == "current") {
+        sendReply(request,"current",IFinal);
+        request.stop();
+        return;
+      }
+
+      if (command == "voltage") {
+        sendReply(request,"voltage",VFinal);
+        request.stop();
+        return;
+      }
+
+      if (command == "power") {
+        sendReply(request,"power",VFinal*IFinal);
+        request.stop();
+        return;
+      }
+
+      if (command == "switch") {
+        sendReply(request,"switch",digitalRead(RELAYPIN));
+        request.stop();
+        return;
+      }
+
+      if (command == "switch/0") {
+        digitalWrite(RELAYPIN, 0);
+        sendReply(request,"switch",digitalRead(RELAYPIN));
+        request.stop();
+        return;
+      }
+
+      if (command == "switch/1") {
+        digitalWrite(RELAYPIN, 1);
+        sendReply(request,"switch",digitalRead(RELAYPIN));
+        request.stop();
+        return;
+      }
+
+      if (command == "") {
+        request.print(F("HTTP/1.1 200 OK\nContent-Type: application/json\n\n"));
+        request.print(F("{\"version\":\"1.0.0\","));
+        request.print(F("\"datastreams\":["));
+        request.print(F("{\"id\":\"voltage\",\"current_value\":"));
+        request.print(VFinal);
+        request.println(F("},"));
+        request.print(F("{\"id\":\"current\",\"current_value\":"));
+        request.print(IFinal);
+        request.println(F("},"));
+        request.print(F("{\"id\":\"power\",\"current_value\":"));
+        request.print(VFinal * IFinal);
+        request.println(F("},"));
+        request.print(F("{\"id\":\"switch\",\"current_value\":"));
+        request.print(digitalRead(RELAYPIN));
+        request.println(F("}"));
+        request.println(F("]"));
+        request.println(F("}"));
+        request.stop();
+        return;
+      }
+    }
+
+    request.print(F("HTTP/1.1 404 Not Found\n\n"));
     request.stop();
-  }
+    return;
+
+  }
+}
+
+void sendReply(EthernetClient client, String cmd, float value) {
+  client.print(F("HTTP/1.1 200 OK\nContent-Type: application/json\n\n"));
+  client.print(F("{\"version\":\"1.0.0\","));
+  client.print(F("\"id\":\""));
+  client.print(cmd);
+  client.print(F("\",\"current_value\":"));
+  client.print(value);
+  client.println(F("}"));
 }

 // this method makes a HTTP connection to the server
 void sendData() {
   // check if the feed has been initialized
-  if (settings.feed == 0) {
+  if (settings.feedid == 0) {
     return;
   }
   // try to connect
   EthernetClient client;
   int ret = client.connect(settings.host, settings.port);
   if (ret == 1) {
-    // build json document
-    DBG Serial.print("PUT /v2/feeds/");
-    DBG Serial.println(settings.feed);
-    // send the HTTP PUT request.
     client.print("PUT /v2/feeds/");
-    client.print(settings.feed);
-    client.print(" HTTP/1.1\n");
-    client.print("X-PachubeApiKey: ");
+    client.print(settings.feedid);
+    client.println(".csv HTTP/1.1");
+    client.println("Host: api.xively.com");
+    client.print("X-ApiKey: ");
     client.println(settings.apikey);
-    client.print("User-Agent: ");
-    client.println(MAGIC);
-    client.print("Content-Type: application/json\n");
-    client.print("\n");
-    // here's the actual content of the PUT request:
-    writeDataStream(client);
-    delay(1000);
-    // if there are incoming bytes available
-    // from the server, read them and print them:
-    while (client.available()) {
-      char c = client.read();
-      DBG Serial.print(c);
-    }
-    DBG Serial.print("\n");
+    client.println("Content-Type: text/csv");
+    client.println("Content-Length: 49");
+    client.println();
+
+    char buffer[10];
+
+    dtostrf(IFinal, 2, 3, buffer);
+    client.print("current,");
+    client.println(buffer);
+
+    dtostrf(VFinal, 2, 3, buffer);
+    client.print("voltage,");
+    client.println(buffer);
+
+    dtostrf(VFinal*IFinal, 2, 3, buffer);
+    client.print("power,");
+    client.println(buffer);
+
+    client.print("switch,");
+    client.println(digitalRead(RELAYPIN));
+
     client.stop();
   }
 }
-
-void writeHeader(EthernetClient &request, const char * data) {
-  while (pgm_read_byte(data) != 0x00) {
-    request.write(pgm_read_byte(data++));
-  }
-}
-
-void writeDataStream(EthernetClient &request) {
-  char r[10];
-  request.print("{\"version\":\"1.0.0\",");
-  request.print("\"datastreams\":[");
-  request.print("{\"id\":\"current\",\"current_value\":");
-  request.print(dtostrf (IFinal, 5, 3, r));
-  request.print("},");
-  request.print("{\"id\":\"voltage\",\"current_value\":");
-  request.print(dtostrf (VFinal, 5, 3, r));
-  request.print("},");
-  request.print("{\"id\":\"watts\",\"current_value\":");
-  request.print(dtostrf (VFinal * IFinal, 5, 3, r));
-  request.print("},");
-  request.print("{\"id\":\"switch\", \"current_value\":");
-  request.print(itoa(digitalRead(RELAY_PIN),r,10));
-  request.print("}");
-  request.print("]}");
-}
-
-#endif

 void dumpToSerial() {
   // Print data also on the serial
@@ -495,30 +449,15 @@
   Serial.print(",");
   Serial.print(VFinal * IFinal,3);
   Serial.print(",");
-  Serial.print(digitalRead(RELAY_PIN));
+  Serial.print(digitalRead(RELAYPIN));
   Serial.print(",");
   Serial.print(delta);
   Serial.print(",");
   Serial.print(sleep);
-#ifdef NOETH
-  Serial.print(",");
-  Serial.print("-");
-  Serial.print(",");
-  Serial.print("-");
-  Serial.print(",");
-  Serial.print("-");
-  Serial.print(",");
-  Serial.print("-");
-  Serial.print(",");
-  Serial.print("-");
-  Serial.print(",");
-  Serial.print("-");
-#else
-  Serial.print(",");
-  Serial.print(Ethernet.localIP());
-  Serial.print(",");
-  Serial.print(SERVER_PORT);
-  Serial.print(",");
+  Serial.print(",");
+  Serial.print(settings.feedid);
+  Serial.print(",");
+  Serial.print("http://");
   for (byte thisByte = 0; thisByte < 4; thisByte++) {
     // print the value of each byte of the IP address:
     Serial.print(settings.host[thisByte], DEC);
@@ -526,26 +465,26 @@
       Serial.print(".");
     }
   }
-  Serial.print(",");
-  Serial.print(settings.port);
-  Serial.print(",");
-  Serial.print(settings.feed);
-  Serial.print(",");
-  Serial.print(settings.apikey);
-#endif
-  Serial.print("\n");
-
+  Serial.print(":");
+  Serial.print(settings.port);
+  Serial.print("/v2/feeds/");
+  Serial.print(",");
+  Serial.println(settings.apikey);
 }

 float scaleVoltage(float voltage) {
-  return ( voltage * 5 * (settings.r1 + settings.r2)) / ( settings.r2 * 1024 );
+  float tmp = ( voltage * 5 * (settings.r1 + settings.r2)) / ( settings.r2 * 1024 );
+  return (tmp > 0) ? tmp : 0.0;
 }

 float scaleCurrent(float current) {
-  return ( current * 5000 / 1024  - settings.offset) / settings.sensitivity;
+  float tmp = ( current * 5000 / 1024  - settings.offset) / settings.sensitivity;
+  return (tmp > 0) ? tmp : 0.0;
 }

 void resetSleep(long value) {
   sleep = (value * 4400) / 1000;
   settings.period = value;
 }
+
+


Adding switch to trike box

Adding switch to trike box

--- trikebox/trikebox.ino
+++ trikebox/trikebox.ino
@@ -3,7 +3,7 @@
 //March 4,2013
 //Version 1.0 adapted for OctoWS2811Lib (tested, working...)

-#define BRIGHTNESS_SCALE 0.8
+float brightnessScale = 0.8;
 #include <OctoWS2811.h>

 //OctoWS2811 Defn. Stuff
@@ -46,50 +46,69 @@
 227,229,232,234,236,239,241,244,246,249,251,253,254,255
 };

+bool lastSwitchPosition;

 void setup()
 {
+  Serial.begin(57600);
   pinMode(13, OUTPUT);
+  pinMode(0, INPUT_PULLUP);
   leds.begin();
   leds.show();
+  delay(100);
+}
+
+unsigned long frameCount=25500;  // arbitrary seed to calculate the three time displacement variables t,t2,t3
+
+void checkSwitch() {
+  bool off = digitalRead(0);
+  if (off && brightnessScale > 0) {
+    brightnessScale -= 0.01;
+  } else if (!off && brightnessScale < 0.8) {
+    brightnessScale += 0.01;
+  }
+  if (!off && lastSwitchPosition == true) {
+    // Do something?
+  }
+  lastSwitchPosition = off;
 }

-void loop()
-{
-  unsigned long frameCount=25500;  // arbitrary seed to calculate the three time displacement variables t,t2,t3
-  while(1) {
-    frameCount++ ;
-    uint16_t t = fastCosineCalc((42 * frameCount)/100);  //time displacement - fiddle with these til it looks good...
-    uint16_t t2 = fastCosineCalc((35 * frameCount)/100);
-    uint16_t t3 = fastCosineCalc((38 * frameCount)/100);
+void loop() {
+  checkSwitch();
+
+  frameCount++;
+  uint16_t t = fastCosineCalc((42 * frameCount)/100);  //time displacement - fiddle with these til it looks good...
+  uint16_t t2 = fastCosineCalc((35 * frameCount)/100);
+  uint16_t t3 = fastCosineCalc((38 * frameCount)/100);

-    for (uint8_t y = 0; y < ROWS_LEDs; y++) {
-      int left2Right, pixelIndex;
-      if (((y % (ROWS_LEDs/8)) & 1) == 0) {
-        left2Right = 1;
-        pixelIndex = y * COLS_LEDs;
-      } else {
-        left2Right = -1;
-        pixelIndex = (y + 1) * COLS_LEDs - 1;
-      }
-      for (uint8_t x = 0; x < COLS_LEDs ; x++) {
-        //Calculate 3 seperate plasma waves, one for each color channel
-        uint8_t r = fastCosineCalc(((x << 3) + (t >> 1) + fastCosineCalc((t2 + (y << 3))))) * BRIGHTNESS_SCALE;
-        uint8_t g = fastCosineCalc(((y << 3) + t + fastCosineCalc(((t3 >> 2) + (x << 3))))) * BRIGHTNESS_SCALE;
-        uint8_t b = fastCosineCalc(((y << 3) + t2 + fastCosineCalc((t + x + (g >> 2))))) * BRIGHTNESS_SCALE;
-        //uncomment the following to enable gamma correction
-        //r=pgm_read_byte_near(exp_gamma+r);
-        //g=pgm_read_byte_near(exp_gamma+g);
-        //b=pgm_read_byte_near(exp_gamma+b);
-        leds.setPixel(pixelIndex, ((r << 16) | (g << 8) | b));
-	pixelIndex += left2Right;
-      }
+  for (uint8_t y = 0; y < ROWS_LEDs; y++) {
+    int left2Right, pixelIndex;
+    if (((y % (ROWS_LEDs/8)) & 1) == 0) {
+      left2Right = 1;
+      pixelIndex = y * COLS_LEDs;
+    } else {
+      left2Right = -1;
+      pixelIndex = (y + 1) * COLS_LEDs - 1;
     }
-    digitalWrite(13, HIGH);
-    leds.show();  // not sure if this function is needed  to update each frame
-    digitalWrite(13, LOW);
+    for (uint8_t x = 0; x < COLS_LEDs ; x++) {
+      //Calculate 3 seperate plasma waves, one for each color channel
+
+      uint8_t r = fastCosineCalc(((x << 3) + (t >> 1) + fastCosineCalc((t2 + (y << 3))))) * brightnessScale;
+      uint8_t g = fastCosineCalc(((y << 3) + t + fastCosineCalc(((t3 >> 2) + (x << 3))))) * brightnessScale;
+      uint8_t b = fastCosineCalc(((y << 3) + t2 + fastCosineCalc((t + x + (g >> 2))))) * brightnessScale;
+
+      //uncomment the following to enable gamma correction
+      r = pgm_read_byte_near(exp_gamma+r);
+      g = pgm_read_byte_near(exp_gamma+g);
+      b = pgm_read_byte_near(exp_gamma+b);
+
+      leds.setPixel(pixelIndex, ((r << 16) | (g << 8) | b));
+      pixelIndex += left2Right;
+    }
   }
+
+  leds.show();  // not sure if this function is needed  to update each frame
 }


Update DriverMEGA.ino

Update DriverMEGA.ino

--- DriverBoards/ArduinoMega64/firmware/DriverMEGA/DriverMEGA.ino
+++ DriverBoards/ArduinoMega64/firmware/DriverMEGA/DriverMEGA.ino
@@ -6,6 +6,7 @@
 inline void _discardByte() { _rx_buffer_tail = (rx_buffer_index_t)(_rx_buffer_tail + 1) % SERIAL_RX_BUFFER_SIZE; }

 *** If you are using an IDE >1.6.X you will need to compile with -O3 (optimization speed), in some cases this does not work and you are forced to compile with 1.6. The binaries are also avaialable.
+*** Comment the line power_usart3_disable(); if it gives you an error.

 */


modified service ID

modified service ID

--- angu/angu.ino
+++ angu/angu.ino
@@ -3,11 +3,11 @@
 const int ledPin = 3; // set ledPin to on-board LED
 //                                                        V
 //ID IS A TEST. IT WAS 19B10010-E8F2-537E-4F6C-D104768A1214<<<<<
-BLEService ledService("19B10010-E8F2-537E-4F6C-D104768A1215"); // create service
+BLEService ledService("19B10010-E8F2-537E-4F6C-D104768A1214"); // create service

 // create switch characteristic and allow remote device to read and write
-BLECharacteristic ledCharacteristic("19B10011-E8F2-537E-4F6C-D104768A1215", BLERead | BLEWrite, 20);
+BLECharacteristic ledCharacteristic("19B10011-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite, 20);

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


Clean up Ethernet template

Clean up Ethernet template

--- create/files/Ethernet.ino
+++ create/files/Ethernet.ino
@@ -7,18 +7,20 @@
 WebApp app;

 void setup() {
+  Serial.begin(115200);
+
   while (!Ethernet.begin(mac)) {
     delay(500);
     Serial.print(".");
   }
-
   Serial.println(Ethernet.localIP());

   app.use(staticFiles());
+
   server.begin();
 }

-void loop(){
+void loop() {
   EthernetClient client = server.available();

   if (client.connected()) {


rename contrast function to setContrast

rename contrast function to setContrast

--- Nokia_5110/Nokia_5110.ino
+++ Nokia_5110/Nokia_5110.ino
@@ -14,7 +14,7 @@
 /**
  * @param contrast could be 1 to 17
  */
-void contrast(short contrast){
+void setContrast(short contrast){
     byte list[17] = {0xAF, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF};

     if(contrast < 1 || contrast > 17)
@@ -34,7 +34,7 @@
     digitalWrite(RST, HIGH);

     lcdCommand(0x21); // LCD extended commands
-    contrast(6);
+    setContrast(6);
     lcdCommand(0x04); // set temp coefficent
     lcdCommand(0x14); // LCD bias mode 1:40
     lcdCommand(0x20); // LCD basic commands


Delete redundant MLP arduino code

Delete redundant MLP arduino code

--- ArduinoCodes/MLP_Combined-arduino/MLP_Combined-arduino.ino
+++ ArduinoCodes/MLP_Combined-arduino/MLP_Combined-arduino.ino
@@ -1,126 +0,0 @@
-#include <SoftwareSerial.h>  // 使用arduino內建(軟體序列埠)程式庫
-SoftwareSerial BTSerialPer(10, 11);    // MLP-PERIPHERAL設定軟體序列埠(接收腳RX,傳送腳TX)
-SoftwareSerial BTSerialCen(8, 9);    // MLP-B1-CENTRAL
-
-boolean queryBaud = true;
-
-String ATReturnPer = "";
-String ATReturnCen = "";
-
-int counterRSSI = 0;
-int arrayRSSI[3] = {0};
-int averageRSSI = 0;
-
-void setup()
-{
-  pinMode(13, OUTPUT);
-  digitalWrite(13, HIGH);
-  BTSerialPer.begin(115200);  // 啟動軟體序列埠,設定傳輸速度
-  BTSerialCen.begin(115200);
-  Serial.begin(115200);
-}
-
-void loop()
-{
-  if (queryBaud){
-    Serial.print("Hello, Start MLP Combined arduino\r\n");
-    queryBaud = false;
-  }
-
-  seizeAddrRSSI();
-  if (BTSerialCen.available() > 0)
-  {
-    delay(5);
-    while ( BTSerialCen.available() ){
-      delay(1); // Because return value is too long
-      char c = BTSerialCen.read();
-      ATReturnCen += c;
-    }
-      notifyAddrRSSI( ATReturnCen );
-      ATReturnCen = "";
-  }
-}
-
-void seizeAddrRSSI()
-{
-  delay(10);
-  writeCenMessage("AT+INQ\r\n");
-}
-
-void notifyAddrRSSI( String ATReturnCen )
-{
-  //Bike1
-  int indexINQ = ATReturnCen.indexOf("+INQ: 80:C1:BA:72:DF:E4,FF00,-");
-    if( indexINQ != -1){
-      indexINQ += 30;
-      int RSSISignalInt = 0;
-      RSSISignalInt = (ATReturnCen[indexINQ]-48)*10 + (ATReturnCen[indexINQ+1]-48);
-
-      if( counterRSSI==3 )
-        counterRSSI = 0;
-
-        arrayRSSI[0] = arrayRSSI[1];
-        arrayRSSI[1] = arrayRSSI[2];
-        arrayRSSI[2] = RSSISignalInt;
-
-        averageRSSI = (arrayRSSI[0]+arrayRSSI[1]+arrayRSSI[2]) / 3;
-
-        writePerMessage("RSSI: ");
-        writePerVariable( String(averageRSSI) );
-
-        if( averageRSSI>75 )
-          writePerMessage(" => BikeFar!");
-        else if( averageRSSI<=75 )
-          writePerMessage(" => BikeNear!");
-    }
-  //Store1
-    indexINQ = ATReturnCen.indexOf("+INQ: 80:C1:BE:27:22:18,FF00,-");
-    if( indexINQ != -1){
-      indexINQ += 30;
-      int RSSISignalInt = 0;
-      RSSISignalInt = (ATReturnCen[indexINQ]-48)*10 + (ATReturnCen[indexINQ+1]-48);
-
-      writePerMessage("RSSI: ");
-      writePerVariable( String(RSSISignalInt) );
-
-      if( RSSISignalInt<=75 )
-        writePerMessage(" => Store1Appear!");
-      else
-        writePerMessage("!");
-    }
-  //Store2
-    indexINQ = ATReturnCen.indexOf("+INQ: 80:BC:72:42:65:98,FF00,-");
-    if( indexINQ != -1){
-      indexINQ += 30;
-      int RSSISignalInt = 0;
-      RSSISignalInt = (ATReturnCen[indexINQ]-48)*10 + (ATReturnCen[indexINQ+1]-48);
-
-      writePerMessage("RSSI: ");
-      writePerVariable( String(RSSISignalInt) );
-
-      if( RSSISignalInt<=75 )
-        writePerMessage(" => Store2Appear!");
-      else
-        writePerMessage("!");
-    }
-}
-
-void writePerMessage(char* message){
-  BTSerialPer.write(message);
-}
-void writePerVariable(String variable){
-  char BTSerialVariable[100] = {'\0'};
-
-  variable.toCharArray(BTSerialVariable, 100);
-  BTSerialPer.write(BTSerialVariable);
-}
-
-void writeCenMessage(char* message){
-  BTSerialCen.write(message);
-}
-void writeCenVariable(String variable){
-  char BTSerialVariable[100] = {'\0'};
-
-  variable.toCharArray(BTSerialVariable, 100);
-  BTSerialCen.write(BTSerialVariable);
-}


xbeewifi clean

xbeewifi clean

--- xbeewifi/xbeewifi.ino
+++ xbeewifi/xbeewifi.ino
@@ -17,11 +17,11 @@
 void loop() {
   if(Serial1.available()) {
     JsonObject& root = jsonBuffer.parseObject(Serial1);
+
     int hue = (float)root["hue"] * 255;
     int patternId = root["patternId"];
     float speed = root["speed"];
     float brightness = root["brightness"];
-     // TODO: setOptions(hue, patternId, speed, brightness);
     if (brightness) FastLED.setBrightness(brightness * 255);
   }
   FastLED.show();


got rid of while(1) loop, couldn't find sensor

--- firmware/examples/HDC1000test.ino
+++ firmware/examples/HDC1000test.ino
@@ -22,11 +22,15 @@
 void setup() {
   Serial.begin(9600);
   Serial.println("HDC100x test");
+
+  hdc.begin();
+  delay(15);    // let the chip initialize

-  if (!hdc.begin()) {
+// Not using   couldn't find sensor
+/*  if (!hdc.begin()) {
     Serial.println("Couldn't find sensor!");
     while (1);
-  }
+  }  */
 }


Update N64 Controller to have the same...

...failsafe features as PS2 Controller

--- n64_controller/n64_controller.ino
+++ n64_controller/n64_controller.ino
@@ -16,7 +16,6 @@
 */

 /*
-
   PINOUTS

@@ -39,8 +38,6 @@
   18              A3            Analog YI
   15              A4            Analog XQ
   14              A5            C-Right
-
-
 */

 #define buttonA 2
@@ -120,6 +117,12 @@
 unsigned long autoResetControllerDataStatus = 0; // 0 = Automatic reset is enabled, 1 = Automatic reset is disabled
 unsigned long resetBeforeInputStatus = 0; // 0 = Resetting before inputting is enabled, 1 = Resetting before inputting is disabled
 unsigned long autoDisconnectOnPingTimeout = 0; // 0 = Arduino will disconnect in case of PING time out, that is, when the computer doesn't respond to the Arduino with PONG, 1 = Arduino won't close connection to the computer in case of PING timeout
+unsigned long controllerPowerStatus = 0; // 0 = Controller is ON, 1 = Controller is OFF
+unsigned long readMotorsAlongSendPing = 0; // 0 = Read motors and get Attention leves after sending Ping, 1 = Do not read motors and get Attention leves after sending Ping.
+unsigned long sendInputOnce = 0; // 0 = Send only once, 1 = Send for every iteration of Loop
+
+boolean sentInputOnce = false;
+boolean sendInputOnlyOnce = false;

 unsigned long resetCalled = 0;
 unsigned long resetDone = 0;
@@ -144,6 +147,9 @@
 byte serial_rx_buffer_change_autoreset_controller_status[12];
 byte serial_rx_buffer_toggle_before_input_reset[12];
 byte serial_rx_buffer_toggle_disconnect_on_ping_timeout[12];
+byte serial_rx_buffer_toggle_controller_pwr[12];
+byte serial_rx_buffer_toggle_motors_after_ping[12];
+byte serial_rx_buffer_toggle_send_input_back[12];
 unsigned long serial_rx_buffer_counter = 0;
 unsigned long controller = 0;

@@ -154,6 +160,46 @@
 unsigned int buttonArray[] = {buttonA, buttonB, buttonZ, buttonStart, buttonDUp, buttonDDown, buttonDLeft, buttonDRight, buttonL, buttonR, buttonCUp, buttonCDown, buttonCLeft, buttonCRight};

 void setup() {
+
+  serial_rx_buffer_toggle_controller_pwr[0] = 0x17;
+  serial_rx_buffer_toggle_controller_pwr[1] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[2] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[3] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[4] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[5] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[6] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[7] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[8] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[9] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[10] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[11] = 0x17;
+
+  serial_rx_buffer_toggle_motors_after_ping[0] = 0x19;
+  serial_rx_buffer_toggle_motors_after_ping[1] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[2] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[3] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[4] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[5] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[6] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[7] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[8] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[9] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[10] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[11] = 0x19;
+
+  serial_rx_buffer_toggle_send_input_back[0] = 0x1B;
+  serial_rx_buffer_toggle_send_input_back[1] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[2] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[3] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[4] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[5] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[6] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[7] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[8] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[9] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[10] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[11] = 0x1B;
+
   inputDelay = 0;
   isInputtingDelayed = false;
   isInputting = false;
@@ -285,6 +331,7 @@
   manualResetControllerData();
   toggleBeforeInputReset();
   toggleDisconnectOnPingTimeout();
+  toggleSendInputBack();

   serial_rx_buffer_change_autoreset_controller_status[0] = 0x11;
   serial_rx_buffer_change_autoreset_controller_status[1] = 0x00;
@@ -324,6 +371,45 @@
   serial_rx_buffer_toggle_disconnect_on_ping_timeout[9] = 0x00;
   serial_rx_buffer_toggle_disconnect_on_ping_timeout[10] = 0x00;
   serial_rx_buffer_toggle_disconnect_on_ping_timeout[11] = 0x15;
+
+  serial_rx_buffer_toggle_controller_pwr[0] = 0x17;
+  serial_rx_buffer_toggle_controller_pwr[1] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[2] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[3] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[4] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[5] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[6] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[7] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[8] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[9] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[10] = 0x00;
+  serial_rx_buffer_toggle_controller_pwr[11] = 0x17;
+
+  serial_rx_buffer_toggle_motors_after_ping[0] = 0x19;
+  serial_rx_buffer_toggle_motors_after_ping[1] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[2] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[3] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[4] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[5] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[6] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[7] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[8] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[9] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[10] = 0x00;
+  serial_rx_buffer_toggle_motors_after_ping[11] = 0x19;
+
+  serial_rx_buffer_toggle_send_input_back[0] = 0x1B;
+  serial_rx_buffer_toggle_send_input_back[1] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[2] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[3] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[4] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[5] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[6] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[7] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[8] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[9] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[10] = 0x00;
+  serial_rx_buffer_toggle_send_input_back[11] = 0x1B;

   inputDelay = 0;
   isInputtingDelayed = false;
@@ -527,6 +613,24 @@

   //  Preamble/Postamble = 0x15 for Respond Back to Auto disconnect on PING timeout
   //  Arduino sends data to tell the computer the change was succesful
+
+  //  Preamble/Postamble = 0x16 for Toggle Relay Switch to turn controller ON or OFF
+  //  Arduino receives data to turn controller ON or OFF
+
+  //  Preamble/Postamble = 0x17 for Respond Back to Turning controller ON or OFF
+  //  Arduino sends data to tell the computer the change was succesful
+
+  //  Preamble/Postamble = 0x18 for Toggle Reading Motor status on or off after sending PING
+  //  Arduino receives data to turn controller ReadMotors on or OFF after PING
+
+  //  Preamble/Postamble = 0x19 for Respond Back to Toggle Reading Motor status on or off after sending PING
+  //  Arduino sends data to tell the computer the change was succesful
+
+  //  Preamble/Postamble = 0x1A for toggle Send Input Once or every iteration of Loop
+  //  Arduino sends data to tell the computer the change was succesful
+
+  //  Preamble/Postamble = 0x1B for respond back to Send Input Once or every iteration of Loop
+  //  Arduino sends data to tell the computer the change was succesful
   if (Serial.available() > 0) {

     controller = Serial.readBytes(serial_rx_buffer, sizeof(serial_rx_buffer)) && 0xFF;
@@ -545,6 +649,18 @@
         serial_rx_buffer_controller[serial_rx_buffer_counter] = serial_rx_buffer[serial_rx_buffer_counter];
         serial_rx_buffer_inverted_controller[serial_rx_buffer_counter] = (serial_rx_buffer_controller[serial_rx_buffer_counter]);
       }
+
+      if (sendInputOnce == 0)
+      {
+        sendInputOnlyOnce = true;
+        sentInputOnce = false;
+      }
+      if (sendInputOnce != 0)
+      {
+        sendInputOnlyOnce = false;
+        sentInputOnce = true;
+      }
+
       //Serial.print('\n');
       Serial.flush();
       // Make the button presses actually work
@@ -624,8 +740,20 @@
       Serial.flush();
       toggleDisconnectOnPingTimeout();
     }
+    else if ((serial_rx_buffer[0] == 0x1A) && (serial_rx_buffer[11] == 0x1A)) {
+      //Serial.print("sendInputOnce=");
+      //Serial.println(sendInputOnce);
+      // Choose to Send Input back only once or every iteration of Loop (While inputting)
+      for (serial_rx_buffer_counter = 0; serial_rx_buffer_counter < sizeof(serial_rx_buffer_toggle_send_input_back); serial_rx_buffer_counter++) {
+
+        serial_rx_buffer_toggle_send_input_back[serial_rx_buffer_counter] = serial_rx_buffer[serial_rx_buffer_counter];
+        Serial.write(serial_rx_buffer_toggle_send_input_back[serial_rx_buffer_counter]);
+      }
+      Serial.flush();
+      toggleSendInputBack();
+    }
     //  Get Invalid Command
-    else if ((((serial_rx_buffer[0] < 0x01) || (serial_rx_buffer[0] > 0x15)) && ((serial_rx_buffer[11] < 0x01) || (serial_rx_buffer[11] > 0x15))) && (((serial_rx_buffer[0] != 0xA0) && (serial_rx_buffer[0] != 0xA1)) && ((serial_rx_buffer[11] != 0xA0) && (serial_rx_buffer[11] != 0xA1)))) {
+    else if ((((serial_rx_buffer[0] < 0x01) || (serial_rx_buffer[0] > 0x1B)) && ((serial_rx_buffer[11] < 0x01) || (serial_rx_buffer[11] > 0x1B))) && (((serial_rx_buffer[0] != 0xA0) && (serial_rx_buffer[0] != 0xA1)) && ((serial_rx_buffer[11] != 0xA0) && (serial_rx_buffer[11] != 0xA1)))) {
       for (serial_rx_buffer_counter = 0; serial_rx_buffer_counter < sizeof(serial_rx_buffer_invalid_command); serial_rx_buffer_counter++) {
         //  Pass Serial Buffer to Reset Controller Data Buffer
         serial_rx_buffer_invalid_command[serial_rx_buffer_counter] = serial_rx_buffer[serial_rx_buffer_counter];
@@ -651,6 +779,45 @@
   calculatePong();
   autoResetControllerData();
 } // Close Loop Function
+
+void toggleSendInputBack() {
+  //  This is where we choose to turn the PS2 controller ON or OFF, through a solid-state low-power relay
+  //inputDelay = 0;
+  //isInputtingDelayed = false;
+  //isInputting = false;
+  //autoResetControllerData();
+  //manualResetControllerData();
+  calculatePing();
+  calculatePong();
+  //Serial.print("sendInputOnce=");
+  //Serial.println(sendInputOnce);
+  //Serial.println("");
+  //Serial.print("Changing from ");
+  //Serial.print(autoDisconnectOnPingTimeout);
+  //Serial.print(" to");
+  //Serial.flush();
+  sendInputOnce = serial_rx_buffer_toggle_send_input_back[8];
+  serial_rx_buffer_toggle_send_input_back[0] = 0x1B;
+  serial_rx_buffer_toggle_send_input_back[11] = 0x1B;
+
+  for (serial_rx_buffer_counter = 0; serial_rx_buffer_counter < sizeof(serial_rx_buffer_toggle_send_input_back); serial_rx_buffer_counter++) {
+    //  Write back data as a way to tell the Status changed correctly
+    Serial.write(serial_rx_buffer_toggle_send_input_back[serial_rx_buffer_counter]);
+  }
+  //Serial.flush();
+  //Serial.print(autoDisconnectOnPingTimeout);
+  //Serial.println(" .");
+  //Serial.flush();
+  //autoResetControllerData();
+  //manualResetControllerData();
+  calculatePing();
+  calculatePong();
+  //Serial.print("sendInputOnce=");
+  //Serial.println(sendInputOnce);
+  //inputDelay = 0;
+  //isInputtingDelayed = false;
+  //isInputting = false;
+}

 void toggleBeforeInputReset() {
   //  This is where we choose whether or not the Arduino resets the controller data before executing an input
@@ -1063,10 +1230,29 @@
   }
   if (isInputting == true)
   {
-    for (serial_rx_buffer_counter = 0; serial_rx_buffer_counter < sizeof(serial_rx_buffer_controller); serial_rx_buffer_counter++) {
-      Serial.write(serial_rx_buffer_controller[serial_rx_buffer_counter]); //  This line writes the serial data back to the computer as a way to check if the Arduino isn't interpreting wrong values
-      serial_rx_buffer_inverted_controller[serial_rx_buffer_counter] = (serial_rx_buffer_controller[serial_rx_buffer_counter]);
-    }
+    if (sendInputOnlyOnce == true)
+    {
+      if (sentInputOnce == false)
+      {
+        for (serial_rx_buffer_counter = 0; serial_rx_buffer_counter < sizeof(serial_rx_buffer_controller); serial_rx_buffer_counter++) {
+          Serial.write(serial_rx_buffer_controller[serial_rx_buffer_counter]); //  This line writes the serial data back to the computer as a way to check if the Arduino isn't interpreting wrong values
+          serial_rx_buffer_inverted_controller[serial_rx_buffer_counter] = (serial_rx_buffer_controller[serial_rx_buffer_counter]);
+          sentInputOnce = true;
+        }
+      }
+    }
+
+    if (sendInputOnlyOnce == false)
+    {
+      if (sentInputOnce == true)
+      {
+        for (serial_rx_buffer_counter = 0; serial_rx_buffer_counter < sizeof(serial_rx_buffer_controller); serial_rx_buffer_counter++) {
+          Serial.write(serial_rx_buffer_controller[serial_rx_buffer_counter]); //  This line writes the serial data back to the computer as a way to check if the Arduino isn't interpreting wrong values
+          serial_rx_buffer_inverted_controller[serial_rx_buffer_counter] = (serial_rx_buffer_controller[serial_rx_buffer_counter]);
+        }
+      }
+    }
+
     //Serial.print('\n');
     Serial.flush();
     //  Press Button


コメントの追加

コメントの追加

--- 2_example/example32_test/example32_test.ino
+++ 2_example/example32_test/example32_test.ino
@@ -27,7 +27,7 @@
 #define PIN_SW 0                            // IO 0 にスイッチを接続
 #define AmbientChannelId 725                // チャネルID(整数)
 #define AmbientWriteKey "ad3e53b54fe16764"  // ライトキー(16桁の16進数)
-#define HOST "54.65.206.59"                 //
+#define HOST "54.65.206.59"                 // AmbientのIPアドレス(変更しない)
 #define SSID "1234ABCD"                     // 無線LANアクセスポイントのSSID
 #define PASS "password"                     // パスワード

@@ -41,33 +41,29 @@
     WiFi.begin(SSID,PASS);                  // 無線LANアクセスポイントへ接続
     while(WiFi.status() != WL_CONNECTED){   // 接続に成功するまで待つ
         delay(500);                         // 待ち時間処理
-        Serial.print('.');
-    }Serial.println();
+        Serial.print('.');                  // 「.」をシリアル出力表示
+    }Serial.println();                      // 改行をシリアル出力表示
     Serial.println(WiFi.localIP());         // 本機のIPアドレスをシリアル出力
 }

 void loop(){                                // 繰り返し実行する関数
-    WiFiClient client;
-    unsigned long t0,t1;
+    WiFiClient client;                      // 開発中のWiFiClientを使用してみる
+    unsigned long t0,t1;                    // ボタン押下・解放時刻を保持
     char s[64],data[64],http[384];

     while(digitalRead(PIN_SW));             // Hレベル(スイッチ解放)時に繰り返し
-    t0=millis();
+    t0=millis();                            // 1回目のボタン押し時刻を保持
     while(!digitalRead(PIN_SW));            // ボタンが開放されるまで待つ
-    digitalWrite(PIN_LED,HIGH);
+    digitalWrite(PIN_LED,HIGH);             // LEDを点灯
     delay(8);                               // 8msの待ち時間処理を実行
     while(digitalRead(PIN_SW));             // Hレベル(スイッチ解放)時に繰り返し
-    t1=millis();
-    delay(100);
-    while(!digitalRead(PIN_SW));            // チャタリング防止措置
-    dtostrf(1000.L/(double)(t1-t0),5,2,s);
+    t1=millis();                            // 2回目のボタン押し時刻を保持
+    delay(100);                             // チャタリング防止措置
+    while(!digitalRead(PIN_SW));            // 意図しない繰り返し処理の防止
+    dtostrf(1000.L/(double)(t1-t0),5,2,s);  // 以下、送信データ作成
     sprintf(data,"{\"writeKey\":\"%s\",\"d1\":\"%s\"}",AmbientWriteKey,s);
     Serial.print(s);
     Serial.println(" Hz");
-    if(!client.connect(HOST,80)){
-        Serial.println("connection failed");
-        return;
-    }
     sprintf(http,"POST /api/v2/channels/%d/data HTTP/1.0\r\n",AmbientChannelId);
     sprintf(s,"Host: %s\r\n",HOST);
     strcat(http,s);
@@ -76,8 +72,12 @@
     strcat(http,"Content-Type: application/json\r\n");
     strcat(http,"\r\n");
     strcat(http,data);
-    client.print(http);
-    delay(30);
+    if(!client.connect(HOST,80)){           // AmbientへTCP接続を実行
+        Serial.println("connection failed");    // 接続失敗表示
+        return;                                 // loop関数の先頭へ戻る
+    }
+    client.print(http);                     // TCPによるデータ送信
+    delay(30);                              // 送信完了待ち
     client.stop();                          // クライアントの切断
-    digitalWrite(PIN_LED,LOW);
+    digitalWrite(PIN_LED,LOW);              // LEDの消灯
 }


Got effects working, code needs cleaning up

--- Arduino/linkit_duo_led6/linkit_duo_led6.ino
+++ Arduino/linkit_duo_led6/linkit_duo_led6.ino
@@ -153,20 +153,20 @@
 void shift_buffer(rgb_color * buffer, bool include_effects = true, int max = ANIM_LED_COUNT){
   for(int i = max - 1; i >= 1; i--){
     buffer[i] = buffer[i-1];
-    if(include_effects){
+//    if(include_effects){
       effects[i] = effects[i-1];
-    }
+//    }
   }
 }

 void push_color(rgb_color color, bool display = false, int effect = NO_EFFECT, rgb_color *buffer = colors, int max = ANIM_LED_COUNT){
-  shift_buffer(buffer, effect = LEAVE_EFFECT ? false : true, max);
+  shift_buffer(buffer, true, max);

   buffer[0] = color;

-  if(effect != LEAVE_EFFECT){
+//  if(effect != LEAVE_EFFECT){
     effects[0] = effect;
-  }
+//  }

   if(display){
     display_buffer(buffer);
@@ -529,7 +529,7 @@
     do_power_shift(window, window + DEMO_TOTAL_SIZE);
     window -= DEMO_TOTAL_SIZE;

-    int effect = BREATHE_ON; //random_effect();
+    int effect = random_effect();

     for(int j = DEMO_GAP_SIZE; j < DEMO_TOTAL_SIZE; j++){
       set_color(j, color, false, effect);


added audio stop button

added audio stop button

--- Room_System_Ardu/Room_System_Ardu.ino
+++ Room_System_Ardu/Room_System_Ardu.ino
@@ -50,6 +50,8 @@
 bool Btn2_ON = false;
 bool Btn3_ON = false;

+bool Snooze_Speakers = false;
+
 bool Reading_Lights = false;

 void setup() {
@@ -94,11 +96,17 @@
     Reading_Lights = false;
   }

-  if (Speaker_Power) {
+  if (Speaker_Power && Btn3_ON){
+    Snooze_Speakers = true;
+  }
+  if (Speaker_Power and not Snooze_Speakers) {
     digitalWrite(Speaker_Power_Pin, HIGH);
   }
   else {
     digitalWrite(Speaker_Power_Pin, LOW);
+  }
+  if (not Speaker_Power && Snooze_Speakers){
+    Snooze_Speakers = false;
   }

   // one shot to reset light fade timer


Code tidy

Code tidy

--- WebastoHeaterWBusArduinoInterface.ino
+++ WebastoHeaterWBusArduinoInterface.ino
@@ -52,21 +52,14 @@
 U8GLIB_PCD8544 u8g(10, 9 , 8);

 //Massive (!) buffer for scrolling text/string output
-char value[190];
+char value[200];

 //buffer for text output of date/time
 char textline1[15];
 char textline2[15];

-//uint8_t dt_day = 1;
-//uint8_t dt_month = 1;
-//uint8_t dt_year = 12;
-//uint8_t ti_hour = 1;
-//uint8_t ti_mins = 1;
-
 uint8_t total_lines1 = 0;
 uint8_t first_visible_line1 = 0;
-//uint8_t currentErrorOnScreen = 0;
 uint8_t updateDisplayCounter = 0;
 uint8_t total_menu_items = 7;

@@ -81,7 +74,6 @@

 //Display 84x48 pixels
-
 M2_SPACE(el_menu_space, "w1h2");

 /* DISPLAY FOR INFO PAGES */
@@ -90,12 +82,6 @@
 M2_LIST(list_strlist) = { &el_labelptr, &el_vsb };
 M2_HLIST(el_strlist_hlist, NULL, list_strlist);
 M2_ALIGN(el_infopages_root, "w84w48", &el_strlist_hlist);
-
-/* FAULT DISPLAY*/
-//M2_INFO(el_labelptr2, "w76l5" , &first_visible_line1, &total_lines1, value, fn_shownextfault);
-//M2_LIST(list_strlist2) = { &el_labelptr2, &el_vsb };
-//M2_HLIST(el_strlist_hlist2, NULL, list_strlist2);
-//M2_ALIGN(top_nextfaulttopelement, "w84h48", &el_strlist_hlist2);

 /* CLOCK/IDLE page */
 M2_LABELFN(el_big_label_clock, "f8w64", label_footer);
@@ -105,19 +91,30 @@
 M2_VLIST(vlist_clocklist, NULL, list_clocklist);
 M2_ALIGN(el_bigclock, NULL, &vlist_clocklist);

-/* MAIN MENU */
-M2_STRLIST(el_strlist_menu, "l3w76" , &first_visible_line1, &total_menu_items, el_strlist_mainmenu);
-M2_VSB(el_vsb_menu, "l3w4" , &first_visible_line1, &total_menu_items);
-M2_LIST(list_menu_strlist) = { &el_strlist_menu, &el_vsb_menu };
-M2_HLIST(el_menu_hlist, NULL, list_menu_strlist);
-
-//Footer at bottom of screen
-M2_LABELFN(el_footer_label, NULL, label_footer);
-M2_LABELFN(el_footer_label2, NULL, label_footer2);
-M2_LIST(list_menu2) = { &el_menu_hlist, &el_menu_space, &el_footer_label, &el_footer_label2 };
-M2_VLIST(el_menu_vlist, NULL, list_menu2);
-
-M2_ALIGN(top_buttonmenu, "-0|2w84h48", &el_menu_vlist);
+
+/* SET DATE */
+//Date
+M2_U8NUM(el_dt_day, "c2", 1, 31, &tm.Day);
+M2_LABEL(el_dt_sep1, NULL, "/");
+M2_U8NUM(el_dt_month, "c2", 1, 12, &tm.Month);
+M2_LABEL(el_dt_sep2, NULL, "/20");
+M2_U8NUM(el_dt_year, "c2", 15, 35, &tm.Year);
+M2_LIST(list_date) = { &el_dt_day, &el_dt_sep1, &el_dt_month, &el_dt_sep2, &el_dt_year };
+M2_HLIST(el_date, NULL, list_date);
+//Time
+M2_U8NUM(el_ti_hour, "c2", 0, 23, &tm.Hour);
+M2_LABEL(el_ti_sep1, NULL, ":");
+M2_U8NUM(el_ti_mins, "c2", 0, 59, &tm.Minute);
+M2_LIST(list_time) = { &el_ti_hour, &el_ti_sep1, &el_ti_mins};
+M2_HLIST(el_time, NULL, list_time);
+//Buttons
+M2_BUTTON(el_dt_ok, NULL, "OK", fn_button_confirmdatetime);
+M2_BUTTON(el_dt_cancel, NULL, "CANCEL", fn_button_showhome);
+M2_LIST(list_dt_buttons) = { &el_date, &el_time, &el_dt_ok, &el_dt_cancel };
+//Vertical align/list
+M2_VLIST(el_top_dt2, NULL, list_dt_buttons);
+M2_ALIGN(el_top_dt, NULL, &el_top_dt2);
+

 /* DIALOG */
 M2_LABELFN(el_dialog_label, NULL, fn_value);
@@ -126,34 +123,20 @@
 M2_VLIST(el_dialog_vlist, NULL, list_dialog);
 M2_ALIGN(top_dialog, NULL, &el_dialog_vlist);

-/* SET DATE */
-
-//= Set date menu =
-M2_U8NUM(el_dt_day, "c2", 1, 31, &tm.Day);
-M2_LABEL(el_dt_sep1, NULL, "/");
-M2_U8NUM(el_dt_month, "c2", 1, 12, &tm.Month);
-M2_LABEL(el_dt_sep2, NULL, "/20");
-M2_U8NUM(el_dt_year, "c2", 15, 35, &tm.Year);
-
-M2_LIST(list_date) = { &el_dt_day, &el_dt_sep1, &el_dt_month, &el_dt_sep2, &el_dt_year };
-M2_HLIST(el_date, NULL, list_date);
-
-//= Set time menu =
-M2_U8NUM(el_ti_hour, "c2", 0, 23, &tm.Hour);
-M2_LABEL(el_ti_sep1, NULL, ":");
-M2_U8NUM(el_ti_mins, "c2", 0, 59, &tm.Minute);
-
-M2_LIST(list_time) = { &el_ti_hour, &el_ti_sep1, &el_ti_mins};
-M2_HLIST(el_time, NULL, list_time);
-
-M2_BUTTON(el_dt_ok, NULL, "OK", fn_button_confirmdatetime);
-M2_BUTTON(el_dt_cancel, NULL, "CANCEL", fn_button_showhome);
-
-M2_LIST(list_dt_buttons) = { &el_date, &el_time, &el_dt_ok, &el_dt_cancel };
-
-M2_VLIST(el_top_dt2, NULL, list_dt_buttons);
-M2_ALIGN(el_top_dt, NULL, &el_top_dt2);
-
+
+/* MAIN MENU */
+M2_STRLIST(el_strlist_menu, "l3w76" , &first_visible_line1, &total_menu_items, el_strlist_mainmenu);
+M2_VSB(el_vsb_menu, "l3w4" , &first_visible_line1, &total_menu_items);
+M2_LIST(list_menu_strlist) = { &el_strlist_menu, &el_vsb_menu };
+M2_HLIST(el_menu_hlist, NULL, list_menu_strlist);
+
+//Footer at bottom of screen
+M2_LABELFN(el_footer_label, NULL, label_footer);
+M2_LABELFN(el_footer_label2, NULL, label_footer2);
+M2_LIST(list_menu2) = { &el_menu_hlist, &el_menu_space, &el_footer_label, &el_footer_label2 };
+M2_VLIST(el_menu_vlist, NULL, list_menu2);
+
+M2_ALIGN(top_buttonmenu, "-0|2w84h48", &el_menu_vlist);


* Fix pins to use for data and clock * Fix CO2 unit from ppm -> PPM * Update MQTT server address * No need to dump the raw frames

--- zg01_esp/zg01_esp.ino
+++ zg01_esp/zg01_esp.ino
@@ -6,10 +6,10 @@

 #include "zg01_fsm.h"

-#define PIN_CLOCK   2
-#define PIN_DATA    3
+#define PIN_CLOCK   D1
+#define PIN_DATA    D2

-#define MQTT_HOST   "revspace.nl"
+#define MQTT_HOST   "mosquitto.space.revspace.nl"
 #define MQTT_PORT   1883

 #define TOPIC_CO2       "revspace/sensors/co2"
@@ -54,24 +54,13 @@
         char string[64];
         snprintf(string, sizeof(string), "%d %s", value, unit);
         Serial.print("Publishing ");
-        Serial.print(value);
+        Serial.print(string);
         Serial.print(" to ");
         Serial.print(topic);
         Serial.print("...");
         int result = mqttClient.publish(topic, string, true);
         Serial.println(result ? "OK" : "FAIL");
     }
-}
-
-static void hexdump(const char *buf, int len)
-{
-    char tmp[8];
-    int i;
-    for (i = 0; i < sizeof(buffer); i++) {
-        snprintf(tmp, sizeof(tmp), " %02X", buffer[i]);
-        Serial.print(tmp);
-    }
-    Serial.println();
 }

 void loop(void)
@@ -87,10 +76,6 @@
         unsigned long ms = millis();
         bool ready = zg01_process(ms, data);
         if (ready) {
-            // dump raw buffer
-            Serial.print("RAW:");
-            hexdump(buffer, sizeof(buffer));
-
             // get item and binary value
             uint8_t item = buffer[0];
             uint16_t value = buffer[1] << 8 | buffer[2];
@@ -98,7 +83,7 @@
             switch (item) {
             case 'P':
                 // CO2
-                mqtt_send(TOPIC_CO2, value, "ppm");
+                mqtt_send(TOPIC_CO2, value, "PPM");
                 break;
             case 'A':
                 // humidity


Fix mazeNav compliation errors

Fix mazeNav compliation errors

--- 2018-Firefighter/2018-Firefighter.ino
+++ 2018-Firefighter/2018-Firefighter.ino
@@ -32,7 +32,7 @@

 Ultrasonic frontUltrasonic(FRONT_US_ECHO, FRONT_US_TRIG, true);
 Ultrasonic leftUltrasonic(LEFT_US_ECHO, LEFT_US_TRIG, true);
-Ultrasonic rightUltrasonic(RIGHT_US_ECHO, RIGH_US_TRIG, true);
+Ultrasonic rightUltrasonic(RIGHT_US_ECHO, RIGHT_US_TRIG, true);

 bool checkingMicrophone = true;
 bool hearingStartSound = false;
@@ -126,15 +126,15 @@
 }

 void mazeNav() { //MOVE MY MINION
-  if(frontUltrasonic < 2 && leftUltrasonic < 2){ //robot has wall in front and to left
+  if(frontUltrasonic.getDistance() < 2 && leftUltrasonic.getDistance() < 2){ //robot has wall in front and to left
     moveRight();
     delay(500);
   }
-  else if(frontUltrasonic < 2 && leftUltrasonic >= 2){ //robot has wall in front
+  else if(frontUltrasonic.getDistance() < 2 && leftUltrasonic.getDistance() >= 2){ //robot has wall in front
     moveLeft();
     delay(500);
   }
-  else{ //if(frontUltrasonic >=2 && leftUltrasonic <2), or if (frontUltrasonic >= 2 && leftUltrasonic >= 2): hug the left wall
+  else{ //if(frontUltrasonic.getDistance() >=2 && leftUltrasonic.getDistance() <2), or if (frontUltrasonic.getDistance() >= 2 && leftUltrasonic.getDistance() >= 2): hug the left wall
     moveForward();
     delay(500);
   }


Put back the code...

Put back the code...

--- ComboKeypad/Keypad.ino
+++ ComboKeypad/Keypad.ino
@@ -113,4 +113,51 @@

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

-/*(—+/*----(Function pressButton, If user presses a Button)----*/
+void pressButton(int num, int digRead){
+  if (digRead == 1 && doonce != true) { // If I hit a Button
+   time = millis();   //Starts the 10 second timer
+    input[count] = num + 1; // sends the number 1 into the array at the "count number"
+     count++; // Where to put 4 into the array
+      doonce = true;
+    }
+    int exists;
+
+      for(int a = 0; a < numOfButtons; a++){
+        if(buttonsRead[a] == 0){
+          exists++;
+        }
+      }
+
+      //////////////////////////////////////////////////////////////////////
+      /// So the it doesnt go ON and OFF infinitly, Basically a stopper  ///
+      /// If no button is pressed reset the doonce                       ///
+      //////////////////////////////////////////////////////////////////////
+      if (exists == numOfButtons && doonce == true){
+         doonce = false;
+          delay(50);
+        }
+}   //Function pressButton end
+
+// Functions "Reset"
+void reset() {
+  // Reset everything
+  for (int t = 0; t < numOfCombos; t++) {   //You could aparently declare an int in a for loop... C++ Style?
+    input[t] = 0;   //Zeros the input array
+  }
+   digitalWrite(rightLight, 0);   //Turns the "Green" light off
+    digitalWrite(wrongLight, 0);   //Turns the "Red" light off
+     count = 0;  //Sets the counter to 0
+
+}//Function Reset end
+
+//Function Debug, Prints the count, and what has been pressed
+void debug(){
+  Serial.print("Count = ");
+   Serial.print(count);
+    Serial.print(", |");
+    for(int a = 0; a < numOfCombos; a++){
+     Serial.print(input[a]);   //Prints which number has been pressed
+   }
+   Serial.println();
+}


Update Keypad.ino

Update Keypad.ino

--- ComboKeypad/Keypad.ino
+++ ComboKeypad/Keypad.ino
@@ -9,7 +9,7 @@

 const bool useFiveVoltpin = false;   //Change this if you want to use the
 ///////////////////////////////////////5Volt PIN instead of PIN 2(IN MY CASE)
-//USER VARIABLES, Variables that YOU change for YOUR preferences | end
+//USER VARIABLES, Variables that YOU change for YOUR preferences | END
 ///
 bool doonce = false;   //Button stopper
 int count = 0;   //How many buttens that have been pressed


Update Cool_Light_WriteTag.ino

Update Cool_Light_WriteTag.ino

--- Cool_Light_WriteTag/Cool_Light_WriteTag.ino
+++ Cool_Light_WriteTag/Cool_Light_WriteTag.ino
@@ -13,8 +13,8 @@
 #include <PN532.h>
 #include <NfcAdapter.h>

-//change the number after colon like "0" or "1" or "2".
-#define WRITE_TAG_MESSAGE "color:0"
+//change the number after colon like "1" or "2" or "3".
+#define WRITE_TAG_MESSAGE "color:1"

 PN532_I2C pn532_i2c(Wire);
 NfcAdapter nfc = NfcAdapter(pn532_i2c);
@@ -28,6 +28,9 @@

 void loop() {
     Serial.println("\nPlace a formatted Mifare Classic NFC tag on the reader.");
+    Serial.print("Writing message: <");
+    Serial.print(WRITE_TAG_MESSAGE);
+    Serial.println("> to you NFC tag");
     if (nfc.tagPresent()) {
         NdefMessage message = NdefMessage();
         message.addTextRecord(WRITE_TAG_MESSAGE);


Capacitive Touch sensor working

Capacitive Touch sensor working

--- StripDimmer.ino
+++ StripDimmer.ino
@@ -1,3 +1,4 @@
+#include <CapacitiveSensor.h>

 const int redPin   = 9;
 const int greenPin = 10;
@@ -10,6 +11,13 @@
 int highRed  = 255;
 int highGreen= 245;
 int highBlue = 45;
+
+const int capsens_signal_pin = 4;
+const int capsens_sense_pin = 3;
+
+
+// 10M resistor between pins, add 1n4148 from sense to 5V and 10k from sense to toucharea
+CapacitiveSensor capsense = CapacitiveSensor(capsens_signal_pin,capsens_sense_pin);

 void setup() {
 //  Serial.begin(57600);
@@ -24,16 +32,16 @@
 void loop() {

     dimLow(0);
-    delay(1000);
+

+    waitForTouch();
     dim1();
-    delay(1000);
+    waitForTouch();
     dim2();
-    delay(1000);
+    waitForTouch();
     dim3();
-    delay(1000);
+    waitForTouch();
     dim4();
-    delay(1000);

 //  while (Serial.available() > 0){
 //    char c = Serial.read();
@@ -65,6 +73,10 @@
 //  }

+}
+
+void waitForTouch(){
+  while(capsense.capacitiveSensor(30) < 3000) { };
 }

 void dim1(){


Voltage and current sensors configuration from the serial interface. Use int instead of long and float in order to save some memory.

--- EnerginoEthernet/EnerginoEthernet.ino
+++ EnerginoEthernet/EnerginoEthernet.ino
@@ -13,6 +13,10 @@
  * Supported commands from the serial:
  *  #F<feed>, sets the feed id [default is 0]
  *  #K<key>, sets the COSM authentication key [default is -]
+ *  #A<integer>, sets value of the R1 resistor in Kohm [default is 100]
+ *  #B<integer>, sets value of the R2 resistor in Kohm [default is 10]
+ *  #C<integer>, sets th offset in mV [default is 2500]
+ *  #C<integer>, sets th sensitivity in mV [default is 850]
  *  #P<integer>, sets the period between two updates (in ms) [default is 2000]
  *  #R, resest the configuration to the defaults
  * No updates are sent if the feed id is set to 0
@@ -71,15 +75,11 @@
 IPAddress GW(172,25,18,254);

 // Energino parameters
-long R1 = 100000;
-long R2 = 10000;
-float OFFSET = 2.69;
-float SENSITIVITY = 0.850;
-long PERIOD = 2000;
-
-// Coordinates
-float LAT=51.5235375648154;
-float LON=-0.0807666778564453;
+int R1 = 100;
+int R2 = 10;
+int OFFSET = 2500;
+int SENSITIVITY = 850;
+int PERIOD = 2000;

 // Buffers used for parsing HTTP request lines
 char buffer[STRING_BUFFER_SIZE];
@@ -108,6 +108,10 @@
   char magic[17];
   char apikey[49];
   long period;
+  int r1;
+  int r2;
+  int offset;
+  int sensitivity;
   long feed;
   IPAddress host;
   long port;
@@ -124,10 +128,14 @@
   DBG Serial.println("Writing defaults.");
   strcpy (settings.magic,MAGIC);
   settings.period = PERIOD;
+  settings.r1 = R1;
+  settings.r2 = R2;
+  settings.offset = OFFSET;
+  settings.sensitivity = SENSITIVITY;
   settings.feed = FEED;
   settings.host = HOST;
   settings.port = PORT;
-  strcpy (settings.apikey,KEY);
+  strcpy (settings.apikey,KEY);
 }

 void setup() {
@@ -137,7 +145,7 @@
   pinMode(13,OUTPUT);
   digitalWrite(13, LOW);
   // configuring serial
-  Serial.begin(115200);
+  Serial.begin(115200);
   // Loading setting
   eeprom_read_block((void*)&settings, (void*)0, sizeof(settings));
   if (strcmp(settings.magic, MAGIC) != 0) {
@@ -206,12 +214,31 @@
     }
   }
   else if (cmd == 'P') {
-    long value = atol(inputBytesPtr);
+    int value = atoi(inputBytesPtr);
     if (value > 0) {
       settings.period = value;
     }
-  }
-  else if (cmd == 'K') {
+  } else if (cmd == 'A') {
+    int value = atoi(inputBytesPtr);
+    if (value >= 0) {
+      settings.r1 = value;
+    }
+  } else if (cmd == 'B') {
+    int value = atoi(inputBytesPtr);
+    if (value >= 0) {
+      settings.r2 = value;
+    }
+  } else if (cmd == 'C') {
+    int value = atoi(inputBytesPtr);
+    if (value >= 0) {
+      settings.offset = value;
+    }
+  } else if (cmd == 'D') {
+    int value = atoi(inputBytesPtr);
+    if (value >= 0) {
+      settings.sensitivity = value;
+    }
+  } else if (cmd == 'K') {
     strncpy(settings.apikey, inputBytes,49);
     settings.apikey[48] = '\0';
   }
@@ -234,7 +261,6 @@
       DBG Serial.println(value);
       settings.port = value;
     }
-
   }
   else if (cmd == 'R') {
     reset();
@@ -368,8 +394,8 @@
 }

 char * getDatastreams() {
-  float i = getCurrent(A0, OFFSET, SENSITIVITY);
-  float v = getVoltage(A1, R1, R2);
+  float i = getCurrent(A0, settings.offset, settings.sensitivity);
+  float v = getVoltage(A1, settings.r1, settings.r2);
   strcpy (buffer,"{\"version\":\"1.0.0\",");
   strcat (buffer,"\"datastreams\":[");
   strcat (buffer,"{\"id\":\"current\",\"current_value\":\"");
@@ -384,11 +410,7 @@
   strcat (buffer,"{\"id\":\"switch\", \"current_value\":\"");
   strcat (buffer,itoa(digitalRead(RELAY_PIN),r,10));
   strcat (buffer,"\"}");
-  strcat (buffer,"],\"location\":{\"lat\":");
-  strcat (buffer,dtostrf (LAT, 8, 5, r));
-  strcat (buffer,",\"lon\":");
-  strcat (buffer,dtostrf (LON, 8, 5, r));
-  strcat (buffer,"}}");
+  strcat (buffer,"]}");
   // Print data also on the serial
   Serial.print("#");
   Serial.print(MAGIC);
@@ -428,7 +450,7 @@
   return buffer;
 }

-float getVoltage(int pin, long r1, long r2) {
+float getVoltage(int pin, int r1, int r2) {
   long readings = 0;
   for(int i = 0; i < SAMPLES; i++) {
     readings += analogRead(pin);
@@ -443,6 +465,5 @@
     readings += analogRead(pin);
   }
   long IRaw = readings / SAMPLES;
-  return ((float) IRaw * 5 / ( 1024 ) - offset) / sensitivity;
-}
-
+  return ((float) IRaw * 5 * 1000 / 1024  - offset) / sensitivity;
+}


Use a init task so OS resources can be directly used

Also start the scheduler which was not done yet.

--- Esp32Application/Esp32Application.ino
+++ Esp32Application/Esp32Application.ino
@@ -25,6 +25,9 @@
  *
  * The MLC2 application for the ESP32, using the Arduino core.
  */
+
+#include <freertos/FreeRTOS.h>
+#include <freertos/task.h>

 #include "LoggingTask.h"

@@ -56,7 +59,7 @@
     PRIORITY_CRITICAL = 3
 };

-void setup()
+static void initTask(void* pvParameters)
 {
     // Initialize logging
     Serial.begin(115200);
@@ -97,11 +100,27 @@
     IPatch* pPatch(gs_pConcert->getPatch(gs_pConcert->addPatch()));
     pPatch->setName("test");
     pPatch->activate();
+
+    // Delete ourselves.
+    vTaskDelete(NULL);
 }

+void setup()
+{
+    // Start the init task, which will initialize everything and delete itself.
+    xTaskCreate(initTask,
+                "init",
+                c_defaultStackSize,
+                nullptr,            // no parameters
+                PRIORITY_CRITICAL,
+                nullptr);           // no need to store task handle
+
+    xPortStartScheduler();
+}

 void loop()
 {
+    // Nothing to do, leave everything to the OS.
 }