Add backwards compatibility for attiny devices without eeprom

--- CoreIR.ino
+++ CoreIR.ino
@@ -14,6 +14,10 @@
 //change transponder ID # by setting a different transponder number for tx_id
 long tx_id = 4444444;
 long tx_alt_id = 8901234;
+
+//if using an attiny, comment out the atmega line below otherwise leave as is.
+#define atmega
+
 //CONFIGURATION END

@@ -26,12 +30,14 @@

 // Include eeprom library for usb connectivity
-#include <EEPROM.h>
+#ifdef atmega
+  #include <EEPROM.h>
+  #include "saved.h"
+#endif

 // Include libraries for ir led frequency and speed
 #include "IRrem.h"
 #include "IRsnd.h"
-#include "saved.h"

 IRsend irsend;
@@ -255,15 +261,17 @@
 }

 void setup() {
-  // save the new transponder numbers in eeprom if they are not already there
-  if (EEPROMReadlong(0) != tx_id) {
-    EEPROMWritelong(0, tx_id);
-  }
-  if (EEPROMReadlong(4) != tx_alt_id) {
-    EEPROMWritelong(4, tx_alt_id);
-  }
-  long tx_id = EEPROMReadlong(0);
-  long tx_alt_id = EEPROMReadlong(4);
+  #ifdef atmega
+    // save the new transponder numbers in eeprom if they are not already there
+    if (EEPROMReadlong(0) != tx_id) {
+      EEPROMWritelong(0, tx_id);
+    }
+    if (EEPROMReadlong(4) != tx_alt_id) {
+      EEPROMWritelong(4, tx_alt_id);
+    }
+    long tx_id = EEPROMReadlong(0);
+    long tx_alt_id = EEPROMReadlong(4);
+  #endif
   // set up jumper bridge for alternate ID
   pinMode(bridgePinIn, INPUT);
   digitalWrite(bridgePinIn, HIGH);


Simplified pattern

Simplified pattern

--- Webradio.ino
+++ Webradio.ino
@@ -1,6 +1,6 @@

-/* A pattern to devellop new project using karaclass
+/* A pattern to develop new project using karaclass
  *
  *  Copyright: Jean-Pierre Cocatrix jp@cocatrix.fr
  *  Pattern for end user


Fixed README.md, fixed a typo

Fixed README.md, fixed a typo

--- CFAG42625A0.ino
+++ CFAG42625A0.ino
@@ -94,7 +94,7 @@
 //  #9/D9     |  PB1 | LCD_CS
 // #10/D10    |  PB2 | DAC_CS
 // #11/D11    |  PB3 | HW_MOSI    (hardware SPI)
-// #12/D12    |  PB4 | not used   (would be hardware MISO)
+// #12/D12    |  PB4 | not used   (hardware MISO)
 // #13/D13    |  PB5 | HW_SCK     (hardware SPI)

 // A0 = LCD_A0


music glove midi finished

music glove midi finished

--- musicglove2/musicglove2.ino
+++ musicglove2/musicglove2.ino
@@ -135,6 +135,7 @@
     {44000, 53100, 34200} // white
   };
   String colorary [9] = {"red", "orange", "yellow", "green", "blue", "indigo", "violet", "black", "white"};
+  int switchnum;
   for (int y = 0; y < 9; y++)
   {
     if ((red_color < (ary[0][y] + constanterror)) && (red_color > (ary[0][y] - constanterror)))
@@ -152,30 +153,31 @@
     if ((redMatch == true) && (blueMatch == true) && (greenMatch = true))
     {
       Serial.println(colorary[y]);
-      break;
-    }
-    switch(y)
+      switchnum = y;
+      break;
+    }
+    switch(switchnum)
     {
       case 0:
-      playNote("C", 4, 200);
+      playNote("C", 4, 300);
       break;
       case 1:
-      playNote("D", 4, 200);
+      playNote("D", 4, 300);
       break;
       case 2:
-      playNote("E", 4, 200);
+      playNote("E", 4, 300);
       break;
       case 3:
-      playNote("F", 4, 200);
+      playNote("F", 4, 300);
       break;
       case 4:
-      playNote("G", 4, 200);
+      playNote("G", 4, 300);
       break;
       case 5:
-      playNote("A", 4, 200);
+      playNote("A", 4, 300);
       break;
       case 6:
-      playNote("B", 4, 200);
+      playNote("B", 4, 300);
       break;
     }
   }


Minor sketch tweaks.

Minor sketch tweaks.

These come from an exploratory branch trying to figure out why the
version header causes system errors when downloading.

--- printer.ino
+++ printer.ino
@@ -153,14 +153,16 @@
 char* cacheFilename = "TMP";
 unsigned long content_length = 0;
 boolean statusOk = false;
-#ifdef DEBUG
-    unsigned long start;
-#endif

 void checkForDownload() {
   unsigned long length = 0;
   content_length = 0;
   statusOk = false;
+
+#ifdef DEBUG
+    unsigned long start;
+#endif
+
   if (SD.exists(cacheFilename)) {
     if (SD.remove(cacheFilename)) {
       debug("Cleared cache");
@@ -180,9 +182,11 @@
     client.print("X-Printer-Version: "); client.println(sketchVersion);
     client.println();
     boolean parsingHeader = true;
+
 #ifdef DEBUG
     start = millis();
 #endif
+
     while(client.connected()) {
       debug("Still connected");
       while(client.available()) {
@@ -219,16 +223,17 @@
           downloadWaiting = true;
           digitalWrite(readyLED, HIGH);
         }
-      } else {
+      }
+#ifdef DEBUG
+      else {
         debug2("Failure, content length was ", content_length);
-        if (content_length != length)
-          debug2("but length was ", length);
-        if (content_length != cache.size())
-          debug2("but cache size was ", cache.size());
-        systemError(); // you should probably reboot
+        if (content_length != length) debug2("but length was ", length);
+        if (content_length != cache.size()) debug2("but cache size was ", cache.size());
+        systemError();
       }
+#endif
     } else {
-      debug("Response code wasn't 200");
+      debug("Response code != 200");
       recoverableError();
     }
   } else {
@@ -239,9 +244,9 @@
   cache.close();

 #ifdef DEBUG
-    unsigned long duration = millis() - start;
-    debug2("Total bytes: ", length);
-    debug2("Duration: ", duration);
+  unsigned long duration = millis() - start;
+  debug2("Total bytes: ", length);
+  debug2("Duration: ", duration);
 #endif
 }


Improve reliability of first-boot ID generation.

This should fix issue #19.

We've seen a few reports of ID generation failing, resulting in an ID of
the form "i%ff%ff%ff%ff". We inspected a brand new Arduino Ethernet and
found that the first byte of its EEPROM was not 255 as the documentation
suggests, but 105 (ASCII i). This would explain why the ID wasn't
generated.

We could've checked for 105 as the first byte directly, since that's not
a valid first character for an ID (it should be a number), but that felt
more risky. We're also not 100% sure that Arduinos will always have the
first byte set to 105, so this fix should be a bit more permissive of
any other first-byte weirdness that other Arduino models have.

--- printer.ino
+++ printer.ino
@@ -39,7 +39,7 @@
 char printerId[17]; // the unique ID for this printer.

 void initSettings() {
-  if (EEPROM.read(idAddress) == 255) {
+  if ((EEPROM.read(idAddress) == 255) || (EEPROM.read(idAddress+1) == 255)) {
     debug("Generating new printer ID.");
     randomSeed(analogRead(0) * analogRead(5));
     for(int i = 0; i < 16; i += 2) {


There are no interrupts you are looking for.

--- zamek.ino
+++ zamek.ino
@@ -52,10 +52,12 @@
 #define REED_INTERRUPT 0
 //pin D3
 #define SWITCH_INTERRUPT 1
+
 //workaround for PROGMEM bug in gcc-c++
 #define PROG_MEM __attribute__((section(".progmem.mydata")))

 #include "progmem.c"
+
 byte numOfCards = sizeof(cards)/sizeof(char*);

 char buffer[BUFSIZE];
@@ -64,20 +66,10 @@
 byte pos = 0;
 Servo servo;

-//as we cannot use servo calls in methods attached to interrupts, so...
-volatile boolean servoDo = false;
 //equal to led's status
 volatile boolean isOpened = false;

-void attachInterrupts(){
-	attachInterrupt(REED_INTERRUPT, closeDoor,  FALLING);
-	attachInterrupt(SWITCH_INTERRUPT, toggleDoor, FALLING);
-}
-
-void detachInterrupts(){
-	detachInterrupt(REED_INTERRUPT);
-	detachInterrupt(SWITCH_INTERRUPT);
-}
+

 void setup() {
 	#ifdef PROD
@@ -90,34 +82,28 @@
 	//enable internal pull-ups
 	digitalWrite(2, HIGH); //INT0
 	digitalWrite(3, HIGH); //INT1
-	//attach interrupts
-	attachInterrupts();
 	//set mode output for led
 	pinMode(13, OUTPUT);
 }

+
+volatile bool lastReedState = false;
+volatile bool lastSwitchState = true;
+
 void loop() {
-	//poor man's state machine!
-	if(servoDo){
-		//disable interrupts during rotation
-		detachInterrupts();
-
-		servoDo = false;
-
-		servo.attach(9);
-		if(isOpened){
-			//clockwise
-			servo.write(180);
-		}else{
-			//counter-clockwise
-			servo.write(0);
-		}
-		delay(2000);
-		servo.detach();
-
-		//re-enable interrupts
-		attachInterrupts();
-	}
+        if(lastSwitchState == false and !digitalRead(2)){
+          toggleDoor();
+          lastSwitchState=true;
+        }else if(lastSwitchState == true and digitalRead(2)){
+          lastSwitchState = false;
+        }
+
+        if(lastReedState == true and !digitalRead(3)){
+          closeDoor();
+          lastReedState=false;
+        }else if(lastReedState == false and digitalRead(3)){
+          lastReedState=true;
+        }
 }

 #ifdef DEBUG
@@ -244,11 +230,25 @@
 	return index%(BUFSIZE);
 }

+
+void servoDo(){
+		servo.attach(9);
+		if(isOpened){
+			//clockwise
+			servo.write(180);
+		}else{
+			//counter-clockwise
+			servo.write(0);
+		}
+		delay(2000);
+		servo.detach();
+}
+
 void openDoor(){
 	if(isOpened == false){
 		digitalWrite(13, HIGH);
 		isOpened = true;
-		servoDo = true;
+                servoDo();
 	}
 }

@@ -257,7 +257,7 @@
 		cleanBuffer();
 		digitalWrite(13, LOW);
 		isOpened = false;
-		servoDo = true;
+		servoDo();
 	}
 }


Delay forever after tuning.

Delay forever after tuning.


Update Example Program

Update Example Program

--- Example_Cylinder_ABBA/Example_Cylinder_ABBA.ino
+++ Example_Cylinder_ABBA/Example_Cylinder_ABBA.ino
@@ -1,35 +1,51 @@
 #include <Cylinder.h>

-int START = 2;int STOP = 3;
-int MIN_A = 4;int MAX_A = 5;
-int MIN_B = 6;int MAX_B = 7;
-int AF = 8;int AB = 9;
-int BF = 10;int BB = 11;
+int START = 2; // Tombol / Sensor start
+int STOP = 3; // Tombol / Sensor Stop
+int MIN_A = 4; // Limit Switch Silinder A (Min)
+int MAX_A = 5; // Limit Switch Silinder A (Max)
+int MIN_B = 6; // Limit Switch Silinder B (Min)
+int MAX_B = 7; // Limit Switch Silinder B (Max)
+int AF = 8; // Silinder A Push
+int AB = 9; // Silinder A Pull
+int BF = 10; // Silinder B Push
+int BB = 11; // Silinder B Pull
+Cylinder silA(MAX_A,MIN_A,AF,AB); // Silinder A Objek
+Cylinder silB(MAX_B,MIN_B,BF,BB); // Silinder B Objek
 int watcher = 0;
-Cylinder silA(MAX_A,MIN_A,AF,AB);
-Cylinder silB(MAX_B,MIN_B,BF,BB);

 void setup() {
   pinMode(START,INPUT);
   pinMode(STOP,INPUT);
-  silA.setState(LOW);
+  silA.setState(HIGH); // Kondisi awal silinder A max, silinder B min
   silB.setState(LOW);
   watcher = 0;
 }

 void loop() {
-  if ((digitalRead(START) == HIGH) && (silA.getState() == LOW) && (silB.getState() == LOW)) {
+  if ((digitalRead(START) == HIGH) && (silA.getState() == HIGH) && (silB.getState() == LOW))
+  {
+    //  Jika tombol / sensor start aktif, silinder A max, dan silinder B min
+    silA.setState(LOW);
+    silB.setState(LOW);
+  }
+  else if ((silA.getState() == LOW) && (silB.getState() == LOW) && (watcher == 0))
+  {
+    //  Jika silinder A min, dan silinder B min (1)
+    silA.setState(LOW);
+    silB.setState(HIGH);
+    watcher = 1;
+  }
+  else if ((silA.getState() == LOW) && (silB.getState() == HIGH))
+  {
+    //  Jika silinder A min, dan silinder B max
+    silA.setState(LOW);
+    silB.setState(LOW);
+  }
+  else if ((silA.getState() == LOW) && (silB.getState() == LOW) && (watcher == 1))
+  {
+    //  Jika silinder A min, dan silinder B min (2)
     silA.setState(HIGH);
-    silB.setState(LOW);
-  } else if ((silA.getState() == HIGH) && (silB.getState() == LOW)) {
-    silA.setState(HIGH);
-    silB.setState(HIGH);
-  } else if ((silA.getState() == HIGH) && (silB.getState() == HIGH) && watcher == 0) {
-    silA.setState(HIGH);
-    silB.setState(LOW);
-    watcher = 1;
-  } else if ((silA.getState() == HIGH) && (silB.getState() == LOW) && watcher == 1) {
-    silA.setState(LOW);
     silB.setState(LOW);
     watcher = 0;
   }


fixed serial print alignment in USBHost/MouseController example

--- libraries/USBHost/examples/MouseController/MouseController.ino
+++ libraries/USBHost/examples/MouseController/MouseController.ino
@@ -55,9 +55,9 @@
   }
   if (mouse.getButton(RIGHT_BUTTON)) {
     SERIAL_PORT_MONITOR.print("R");
-    SERIAL_PORT_MONITOR.println();
     rightButton = true;
   }
+  SERIAL_PORT_MONITOR.println();
 }

 // This function intercepts mouse button release


Avoid sending out the state on boot (we wanted that -turned out to be a bad idea.

--- lib-arduino/ACNode/examples/SpaceDeur/SpaceDeur.ino
+++ lib-arduino/ACNode/examples/SpaceDeur/SpaceDeur.ino
@@ -264,7 +264,7 @@
 void grote_schakelaar_loop() {
   // debounce
   static unsigned long lst = 0;
-  static int last_grote_schakelaar = -2;
+  static int last_grote_schakelaar = digitalRead(GROTE_SCHAKELAAR_SENSOR);

   if (digitalRead(GROTE_SCHAKELAAR_SENSOR) != last_grote_schakelaar && lst == 0) {
     last_grote_schakelaar = digitalRead(GROTE_SCHAKELAAR_SENSOR);


datafile should store target hits indexed to 1

--- range/arduino/target_module/target_module.ino
+++ range/arduino/target_module/target_module.ino
@@ -163,7 +163,7 @@
     read_marker = read_marker % BUFFER_LINES;
     datafile.print(hit_record[read_marker].timestamp);
     datafile.print(',');
-    datafile.print(hit_record[read_marker].getTarget());
+    datafile.print(hit_record[read_marker].getTarget()+1);
     datafile.println();
   }


Plot PID output in percent

Plot PID output in percent

--- PlainReflow.ino
+++ PlainReflow.ino
@@ -27,7 +27,7 @@
 Thread control_thread = Thread();

 // variables for PID controller
-double PID_setpoint, PID_in, PID_out, PID_out_by_10;
+double PID_setpoint, PID_in, PID_out, PID_out_percent;

 // for slow PWM:
 const int pwm_window = 5000; // 5 seconds
@@ -58,11 +58,11 @@

 void control_callback(void) {
   // control thread
-  PID_setpoint = 250; // constant for testing
+  PID_setpoint = 50; // constant for testing
   PID_in = measure_temperature();

   control_PID.Compute();
-  PID_out_by_10 = PID_out/10;
+  PID_out_percent = PID_out/pwm_window*100;

   unsigned long now = millis();
   if (now - pwm_start_time > pwm_window) {
@@ -175,7 +175,7 @@
   plotter.AddTimeGraph( "Reflow oven variables", 18000, // about 3 minutes
                           "PID Setpoint (°C)", PID_setpoint,
                           "PID Input (°C)", PID_in,
-                          "PID Output (10 ms)", PID_out_by_10,
+                          "PID Output (%)", PID_out_percent,
                           "Oven state (on/off)", oven_is_on);

   // Configure PID controller


Добавлен псевдо режим сна

Добавлен псевдо режим сна

--- main.ino
+++ main.ino
@@ -46,12 +46,24 @@
 	B00001
 };

+static byte	lock_icon[8] = {
+	B01111,
+	B01111,
+	B00011,
+	B00111,
+	B00011,
+	B11111,
+	B11011,
+	B11111
+};
+
 /*bits system_byte*/
 #define RED_SPEED			(1 << 0)	// Включать ли красный свет при уменьшении скорости
 #define AUTO_BACKLIGHT		(1 << 1)	// Включать подсветку экрана по датчику света или нет
 #define AUTO_HEADLIGHT		(1 << 2)	// Включать фару по датчику света или нет
-#define AlARM_STATE			(1 << 3)	// Для того, чтобы даже после сброса сигнализация не выключилась
-#define NEON_ON_DOWNTIME	(1 << 4)	// Плавное свечение нижней подсветки в простое
+#define NEON_ON_DOWNTIME	(1 << 3)	// Плавное свечение нижней подсветки в простое
+#define ALARM_STATE			(1 << 4)	// Для того, чтобы даже после сброса сигнализация не выключилась
+#define ALARM_WRITED		(1 << 5)	// Было ли записано значение о сигнализации в EEPROM

 struct sys_conf {
 	byte	password[6],		// Пароль, для отключения сигнала
@@ -103,6 +115,7 @@
 #define	BUT_SIGNAL			4
 #define BATTERY_ICON		0
 #define SIGNAL_ICON			1
+#define LOCK_ICON			2

 /*Для определения заряда батарей*/
 #define TYPVBG				1.1
@@ -128,7 +141,7 @@
 			distance		= 0.0;	// Расстояние

 byte		system_mode		= 0,
-			alarm_now		= false;
+			deep_sleep		= false;

 /*system_mode*/
 #define SPEED_MODE			0
@@ -179,6 +192,7 @@

 	lcd.createChar(BATTERY_ICON, bat_icon);	// Загрузка иконки батареи
 	lcd.createChar(SIGNAL_ICON, signal_icon);	// Загрузка иконки батареи
+	lcd.createChar(LOCK_ICON, lock_icon);	// Загрузка иконки батареи

 	#ifdef DEBUG
 	lcd.clear();
@@ -289,7 +303,7 @@
 }

 void alarm_sense() {
-	alarm_now	= true;
+	set_bit(btc_config.system_byte, ALARM_STATE);
 }

 void speed_sense() {	// Подсчёт скорости
@@ -317,6 +331,14 @@

 	if ((system_mode != SLEEP_MODE) && (system_mode != SLEEP_MODE) && (bit_seted(btc_config.system_byte, AUTO_BACKLIGHT) == false) && (digitalRead(DISPLAY_LIGHT) == LOW)) {	// Чтобы при выключенной автоподсветке включилась посветка экрана
 		digitalWrite(DISPLAY_LIGHT, HIGH);
+	}
+
+	if ((deep_sleep) && (system_mode == SPEED_MODE)) {
+		return false;
+	}
+
+	if ((deep_sleep) && (analogRead(ACTION_BUTTON) > 5)) {
+		return false;
 	}

 	return true;
@@ -487,8 +509,9 @@
 						count++;
 					}

-					if (count == 3) {
-						alarm_now	= true;
+					if (count >= 3) {
+						set_bit(btc_config.system_byte, ALARM_STATE);
+						system_mode	= ALARM_MODE;
 					} else {
 						input_password();
 						changes	= true;
@@ -1343,5 +1366,68 @@
 }

 void system_sleep() {
-
+	byte	count;
+
+	registerWrite(0);
+	digitalWrite(HEADLIGHT, LOW);
+	digitalWrite(DISPLAY_LIGHT, LOW);
+	digitalWrite(LOWER_LIGHT, LOW);
+	digitalWrite(RED_BACK_LIGHT, LOW);
+
+	deep_sleep	= true;
+
+	while (true) {
+		while ((sys_watch()) && (system_mode == SLEEP_MODE)) {
+			lcd.clear();
+
+			if (hour() < 10)
+				lcd.print(" ");
+
+			lcd.print(hour());
+			lcd.print(":");
+			lcd.print(minute());
+
+			lcd.print(" ");
+			lcd.print(day());
+			lcd.print(".");
+			lcd.print(month());
+			lcd.print(".");
+			lcd.print(year());
+
+			lcd.setCursor(1, 1);
+			lcd.print("I:");
+			lcd.print(bat_state(0));
+			lcd.print("%");
+			lcd.setCursor(8, 1);
+			lcd.print("E:");
+			lcd.print(bat_state(1));
+			lcd.print("%");
+
+			lcd.setCursor(15, 1);
+			lcd.write(LOCK_ICON);
+
+			delay_w(30000);
+		}
+
+		if (system_mode == SLEEP_MODE) {
+			deep_sleep	= false; // Выход из глубокого сна, чтобы можно было хоть что-нибудь ввести
+
+			while ((sys_watch()) && (analogRead(ACTION_BUTTON) > 5));
+
+			for (count	= 0; ((count < 3) && (!read_password())); count++);
+
+			if (count >= 3) {
+				set_bit(btc_config.system_byte, ALARM_STATE);
+				system_mode	= ALARM_MODE;
+				break;
+			} else {
+				break;
+			}
+		}
+	}
+
+	if (system_mode	!= ALARM_MODE)
+		system_mode	= SPEED_MODE;
+
+	deep_sleep	= false;
 }


Tick some boxes, format blank_time, add checkOT method

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

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

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

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


Added child for relay of air conditioner.

--- RelayTemperatureSensor/RelayTemperatureSensor.ino
+++ RelayTemperatureSensor/RelayTemperatureSensor.ino
@@ -1,3 +1,11 @@
+#include <UIPServer.h>
+#include <UIPEthernet.h>
+#include <ethernet_comp.h>
+#include <UIPClient.h>
+#include <Dhcp.h>
+#include <UIPUdp.h>
+#include <Dns.h>
+

 #include <MySensor.h>
 #undef DEBUG
@@ -8,13 +16,15 @@

 // ---- NODE
 #define NODE_ID 110
-#define CHILD_ID_RELAY 1
+#define CHILD_ID_RELAY_AC 2 // Relay for Air conditioner
+#define CHILD_ID_RELAY 1    // Relay for heating
 #define CHILD_ID_TEMP 0

 // ----- RELAY
 #define RELAY_PIN  4  // Arduino Digital I/O pin number for first relay (second on pin+1 etc)
 #define RELAY_ON 1  // GPIO value to write to turn on attached relay
 #define RELAY_OFF 0 // GPIO value to write to turn off attached relay
+#define PUSH_TIMEOUT 500 // Simulate push button on AC with a relay (milliseconds)

 // ----- TEMPERATURE SENSOR
 #define ONE_WIRE_BUS 3 // Pin where dallas sensor is connected
@@ -42,7 +52,7 @@
   // Initialize library and add callback for incoming messages
   hw.begin(incomingMessage, NODE_ID, true);
   // Send the sketch version information to the gateway and Controller
-  hw.sendSketchInfo("Relay-Temperature Sensor", "2.0");
+  hw.sendSketchInfo("Relay-Temperature Sensor", "2.1");

   // --- TEMPERATURE
   // Startup OneWire
@@ -56,6 +66,8 @@

   // --- RELAY
   hw.present(CHILD_ID_RELAY, S_LIGHT);
+  hw.present(CHILD_ID_RELAY_AC, S_LIGHT);
+
   // Then set relay pins in output mode
   pinMode(RELAY_PIN, OUTPUT);
   // Set relay to last known state (using eeprom storage)
@@ -110,8 +122,13 @@
 }

 void incomingMessage(const MyMessage &message) {
+  processHeatingMessage(message);
+  processACMessage(message);
+}
+
+void processHeatingMessage(const MyMessage &message) {
   // We only expect one type of message from controller. But we better check anyway.
-  if (message.type == V_LIGHT) {
+  if (message.sensor == CHILD_ID_RELAY && message.type == V_LIGHT) {
     // Change relay state
     digitalWrite(RELAY_PIN, message.getBool() ? RELAY_ON : RELAY_OFF);
     // Store state in eeprom
@@ -120,4 +137,13 @@
   }
 }

+void processACMessage(const MyMessage &message) {
+  // We only expect one type of message from controller. But we better check anyway.
+  if (message.sensor == CHILD_ID_RELAY_AC && message.type == V_LIGHT) {
+    digitalWrite(RELAY_PIN, RELAY_ON);
+    hw.wait(PUSH_TIMEOUT);
+    digitalWrite(RELAY_PIN, RELAY_OFF);
+    debug(PSTR("Push button: %d \n"), message.sensor);
+  }
+}


Fixed a bug in the serial correction.

Fixed a bug in the serial correction.

--- software/Arduino/ServoController/ServoController.ino
+++ software/Arduino/ServoController/ServoController.ino
@@ -1,9 +1,11 @@
-/**********************************************************************
- * Arduino Uno Program - Controls Servos and Reads IMU                *
- * Project: Eclipse Tracking (2017)                                   *
- * Version: 3.0 (5/07/2017)                                           *
- * Max Bowman / Jeremy Seeman / George Moe                            *
- **********************************************************************/
+/***********************************************************************
+ * Description: Counteracts a change in angle by reading a gyro sensor *
+ * and rotating a stepper motor. Accepts correction factors via serial *
+ * at 115200 baud.                                                     *
+ * Project: Eclipse Tracking (2017)                                    *
+ * @Version 4.0 (5/13/2017)                                            *
+ * @Author Max Bowman / Jeremy Seeman / George Moe                     *
+ ***********************************************************************/
 #include <Stepper.h>
 #include <Wire.h>
 #include <MsTimer2.h>
@@ -35,12 +37,12 @@
 // Orientation data
 float positionChange;

-// Misc.
+// Interrupt flag
 int timer = millis();
 bool update_flag = false; // interrupt flag for executing motor update

 /**
-    Sets up everything
+    Sets up system
 */
 void setup() {
   // Initialize I/O
@@ -48,7 +50,7 @@
   pinMode(LED, OUTPUT);

   // Setup hardware
-  setupIMU();         // Gyro
+  setupIMU(); // Gyro

   // Calibrate the gyro
   calibratedOffset = zeroGyro(calibrationSamples);
@@ -56,9 +58,6 @@
   // Setup motor update interval timer
   MsTimer2::set(motorUpdateRate, updateMotor);
   MsTimer2::start();
-
-  // Blink LED to indicate that initilization has completed!
-  blinkLED(20, 10);
 }

 void loop() {
@@ -69,7 +68,7 @@
     byte negative = 0;
     if (Serial.read() == '1') negative = 1;
     for (int i = 100; i >= 1; i /= 10) {
-      correctionFactor += (Serial.read() - '0') * 100;
+      correctionFactor += (Serial.read() - '0') * i;
     }
     if (negative) correctionFactor = -correctionFactor;
     rotateStepperBy(correctionFactor);
@@ -108,8 +107,36 @@
   imu.settings.device.mAddress = LSM9DS1_M;
   imu.settings.device.agAddress = LSM9DS1_AG;
   while (!imu.begin()) {
-    digitalWrite(LED, HIGH);
+    blinkLED(1000, 1);
   }
+  blinkLED(50, 15);
+}
+
+/**
+    Reads the IMU's gyro
+    @return rate in degrees / ms
+*/
+float readGyro() {
+  if (imu.gyroAvailable()) {
+    imu.readGyro();
+  }
+  return imu.calcGyro(imu.gz) - calibratedOffset;
+}
+
+/**
+    Finds the calibration constant of the
+    gyro.
+    @param number of calibration samples
+*/
+int zeroGyro(int calibrationSamples) {
+  float zSum = 0;
+  for (int i = 0; i < calibrationSamples; i++) {
+    imu.readGyro();
+    float z = imu.calcGyro(imu.gz);
+    zSum += z;
+    delay(10);
+  }
+  return zSum / calibrationSamples;
 }

 /**
@@ -126,17 +153,6 @@
 }

 /**
-    Reads the IMU's gyro
-    @return rate in degrees / ms
-*/
-float readGyro() {
-  if (imu.gyroAvailable()) {
-    imu.readGyro();
-  }
-  return imu.calcGyro(imu.gz) - calibratedOffset;
-}
-
-/**
     Blinks an LED on pin 13
     @param delay in milliseconds
     @param number of blinks
@@ -149,22 +165,3 @@
     delay(del);
   }
 }
-
-/**
-    Finds the calibration constant of the
-    gyro.
-    @param number of calibration samples
-*/
-int zeroGyro(int calibrationSamples) {
-  float zSum = 0;
-  for(int i = 0; i < calibrationSamples; i++) {
-    if(i % 1000 == 0) {
-      blinkLED(500, 1);
-    }
-    imu.readGyro();
-    float z = imu.calcGyro(imu.gz);
-    zSum += z;
-    delay(10);
-  }
-  return zSum / calibrationSamples;
-}


Put dimmerTask at top of file.

Put dimmerTask at top of file.

Arduino 1.8.6 was picky about this order

--- dimmertask.ino
+++ dimmertask.ino
@@ -1,69 +1,3 @@
-bool defaultTimersLoaded()
-{
-  //find 'default.aqu' on selected storage and if present load the timerdata from this file
-  //return true on success
-  //return false on error
-
-  if ( !SPIFFS.exists( defaultTimerFile ) )
-  {
-    ESP_LOGI( TAG, "No default timer file found. [%s]", defaultTimerFile );
-    return false;
-  }
-
-  File f = SPIFFS.open( defaultTimerFile, "r" );
-
-  if ( !f.available() )
-  {
-    ESP_LOGI( TAG, "Error opening default timer file. [%s]", defaultTimerFile );
-    return false;
-  }
-  String lineBuf;
-  byte currentTimer = 0;
-  byte thisChannel;
-  while ( f.position() < f.size() )
-  {
-    lineBuf = f.readStringUntil( '\n' );
-    if ( lineBuf.indexOf( "[" ) > -1 )
-    {
-      String thisChannelStr;
-      thisChannelStr = lineBuf.substring( lineBuf.indexOf("[") + 1, lineBuf.indexOf("]") );
-      thisChannel = thisChannelStr.toInt();
-      currentTimer = 0;
-    }
-    else
-    {
-      String thisPercentage;
-      String thisTime;
-      thisTime = lineBuf.substring( 0, lineBuf.indexOf(",") );
-      thisPercentage = lineBuf.substring( lineBuf.indexOf(",") + 1 );
-      channel[thisChannel].timer[currentTimer].time = thisTime.toInt();
-      channel[thisChannel].timer[currentTimer].percentage = thisPercentage.toInt();
-      currentTimer++;
-      channel[thisChannel].numberOfTimers = currentTimer;
-    }
-  }
-  f.close();
-  //add the 24:00 timers ( copy of timer percentage no: 0 )
-  for ( thisChannel = 0; thisChannel < NUMBER_OF_CHANNELS; thisChannel++ )
-  {
-    channel[thisChannel].timer[channel[thisChannel].numberOfTimers].time = 86400;
-    channel[thisChannel].timer[channel[thisChannel].numberOfTimers].percentage = channel[thisChannel].timer[0].percentage;
-  }
-  return true;
-}
-
-void setEmptyTimers()
-{
-  for ( byte channelNumber = 0; channelNumber < NUMBER_OF_CHANNELS; channelNumber++)
-  {
-    channel[channelNumber].timer[0].time = 0;
-    channel[channelNumber].timer[0].percentage = 0;
-    channel[channelNumber].timer[1].time = 86400;
-    channel[channelNumber].timer[1].percentage = 0;
-    channel[channelNumber].numberOfTimers = 1;
-  }
-}
-
 void IRAM_ATTR dimmerTask ( void * pvParameters )
 {
   const TickType_t dimmerTaskdelayTime = 1000 / UPDATE_FREQ_LEDS / portTICK_PERIOD_MS;
@@ -173,6 +107,75 @@
   }
 }

+bool defaultTimersLoaded()
+{
+  //find 'default.aqu' on selected storage and if present load the timerdata from this file
+  //return true on success
+  //return false on error
+
+  if ( !SPIFFS.exists( defaultTimerFile ) )
+  {
+    ESP_LOGI( TAG, "No default timer file found. [%s]", defaultTimerFile );
+    return false;
+  }
+
+  File f = SPIFFS.open( defaultTimerFile, "r" );
+
+  if ( !f.available() )
+  {
+    ESP_LOGI( TAG, "Error opening default timer file. [%s]", defaultTimerFile );
+    return false;
+  }
+  String lineBuf;
+  byte currentTimer = 0;
+  byte thisChannel;
+  while ( f.position() < f.size() )
+  {
+    lineBuf = f.readStringUntil( '\n' );
+    if ( lineBuf.indexOf( "[" ) > -1 )
+    {
+      String thisChannelStr;
+      thisChannelStr = lineBuf.substring( lineBuf.indexOf("[") + 1, lineBuf.indexOf("]") );
+      thisChannel = thisChannelStr.toInt();
+      currentTimer = 0;
+    }
+    else if ( currentTimer < MAX_TIMERS - 1 )
+    {
+      String thisPercentage;
+      String thisTime;
+      thisTime = lineBuf.substring( 0, lineBuf.indexOf(",") );
+      thisPercentage = lineBuf.substring( lineBuf.indexOf(",") + 1 );
+      channel[thisChannel].timer[currentTimer].time = thisTime.toInt();
+      channel[thisChannel].timer[currentTimer].percentage = thisPercentage.toInt();
+      currentTimer++;
+      channel[thisChannel].numberOfTimers = currentTimer;
+    }
+
+  }
+  f.close();
+  //add the 24:00 timers ( copy of timer percentage no: 0 )
+  for ( thisChannel = 0; thisChannel < NUMBER_OF_CHANNELS; thisChannel++ )
+  {
+    channel[thisChannel].timer[channel[thisChannel].numberOfTimers].time = 86400;
+    channel[thisChannel].timer[channel[thisChannel].numberOfTimers].percentage = channel[thisChannel].timer[0].percentage;
+    currentTimer++;
+    channel[thisChannel].numberOfTimers = currentTimer;
+  }
+  return true;
+}
+
+void setEmptyTimers()
+{
+  for ( byte channelNumber = 0; channelNumber < NUMBER_OF_CHANNELS; channelNumber++)
+  {
+    channel[channelNumber].timer[0].time = 0;
+    channel[channelNumber].timer[0].percentage = 0;
+    channel[channelNumber].timer[1].time = 86400;
+    channel[channelNumber].timer[1].percentage = 0;
+    channel[channelNumber].numberOfTimers = 1;
+  }
+}
+
 void setupDimmerPWMfrequency( const double frequency, const uint8_t numberOfBits )
 {
   /* Setup timers and pwm bit depth */


fixed adding sensors logic, added debug option

--- jenny5-firmware/jenny5-firmware.ino
+++ jenny5-firmware/jenny5-firmware.ino
@@ -7,7 +7,7 @@
 #include "jenny5_types.h"

 byte potentiometers_pins[4] = {0, 1, 2, 3};
-t_limit_pair potentiometer_limits[4] = {{500, 1000}, {0, 1023}, {200, 600}, {300, 600}};
+t_limit_pair potentiometer_limits[4] = {{500, 1000}, {500, 1023}, {200, 600}, {300, 600}};

 byte ultrasonic_trig_pins[2] = {48, 50};
 byte ultrasonic_echo_pins[2] = {49, 51};
@@ -45,6 +45,7 @@
   Serial.println(F("Bx# // Gets the status of the button x."));
   Serial.println(F("Px# // Gets the position of the potentiometer x."));
   Serial.println(F("Ix# // Gets the status of infrared sensor x."));
+  Serial.println(F("G# // Prints for each motor: [sensor index, sensor type, sensor value, is whithin limits]"));
 //  Serial.println(F("PL# // sets the min (lower) position for potentiometer x."));
 //  Serial.println(F("PU# // sets the max (upper) position for potentiometer x."));

@@ -100,7 +101,7 @@
             // now I have to add sensors one by one
             int j = i + 3;
             while (j < str_length){
-              if (tmp_str[i] == 'P' || tmp_str[i] == 'p'){
+              if (tmp_str[j] == 'P' || tmp_str[j] == 'p'){
                 int sensor_index;
                 sscanf(tmp_str + j + 1, "%d", &sensor_index);
                 motors_control.add_sensor(motor_index, POTENTIOMETER, sensor_index);
@@ -130,15 +131,38 @@
             //Serial.print(infrareds_control.get_infrared_value(sensor_index));
             i++;
           }
+        else
+          if (tmp_str[i] == 'G' || tmp_str[i] == 'g'){// for debugging purpose
+            int index;
+            for(index = 0; index < motors_control.num_motors; index++) {
+              Serial.print("Motor: ");
+              Serial.println(index);
+              for (byte j = 0 ; j < motors_control.sensors[index].count ; ++j) {
+                byte sensor_index = motors_control.sensors[index].sensors_array[j].index;
+                byte type = motors_control.sensors[index].sensors_array[j].sensor_type;
+                Serial.print("Sensor index: ");
+                Serial.print(sensor_index);
+                Serial.print(", Type: ");
+
+                if (POTENTIOMETER == type)
+                  Serial.print("potentiometer, Value: ");
+                  Serial.print(potentiometers_control.getPotentiometerValue(sensor_index));
+                  Serial.print(", Is whitin limits: ");
+                  Serial.println(potentiometers_control.isWithinLimits(sensor_index));
+                }
+            }
+            i++;
+        }
     }
     else
       i++;
   }
 }
+
 //--------------------------------------------------------------------------------------------
 //Main loop
 void loop() {
-
+
   if (!is_command_running && (Serial.available() || current_buffer[0])) {
     int num_read = 0;
     char arduino_buffer[65];


Small Fix

Small Fix

--- Master.ino
+++ Master.ino
@@ -34,8 +34,6 @@
 String inputHOLD; //string to hold inputs
 bool buff[12]; //buffer to store recived and to be send packets
 char ch; //store recived char and char to send
-short writtenCH = 0; //to count chars before new line
-
 colorBit th_Val[8]; //strore all possible combs
 uint16_t r, g, b, c; //to store env data

@@ -374,6 +372,7 @@

 void loop()
 {
+  short writtenCH = 0; //to count chars before new line
   bool err = 0;
   tcs.getRawData(&r, &g, &b, &c);
   if(g > th_Val[2].g_t)
@@ -457,9 +456,7 @@
   th_Val[0].r_t = ((float) r * thErrOFF);
   th_Val[0].g_t = ((float) g * thErrOFF);
   th_Val[0].b_t = ((float) b * thErrOFF);
-  Serial.print("\nWaiting for threshold sequence or type ");
-  Serial.print(sync);
-  Serial.println(" to send threshold sequence");
+  Serial.print("\nWaiting for threshold sequence");
   uint16_t r_h, g_h, b_h;
   setupMain: //come back here untill sync seq start
   if (Serial.available() > 0) //if there is an input data
@@ -817,6 +814,7 @@
       flashDotOrDash(redLED, false);
       flashDotOrDash(blueLED, false);
       flashDotOrDash(greenLED, false);
+      Serial.print(" ");
     delay(trnsDELAY);
   }
   Serial.println(); //for testing **************************************


revert change

revert change

microrontroller dependent register access

--- MewPro.ino
+++ MewPro.ino
@@ -204,8 +204,8 @@
 void loop()
 {
   // Attach or detach bacpac
-  //if (digitalRead(HBUSRDY) == HIGH) {
-  if ((PINC & _BV(0)) == 1) { // speed up!
+  if (digitalRead(HBUSRDY) == HIGH) {
+  //if ((PINC & _BV(0)) == 1) { // speed up!
     if (lastHerobusState != HIGH) {
 #if !defined(USE_I2C_PROXY)
       pinMode(I2CINT, OUTPUT); digitalWrite(I2CINT, HIGH);


add an interval between two measurements

--- examples/UltrasonicDisplayOnTerm/UltrasonicDisplayOnTerm.ino
+++ examples/UltrasonicDisplayOnTerm/UltrasonicDisplayOnTerm.ino
@@ -49,12 +49,15 @@
 {
 	long RangeInInches;
 	long RangeInCentimeters;
+
+	Serial.println("The distance to obstacles in front is: ");
 	RangeInInches = ultrasonic.MeasureInInches();
-	RangeInCentimeters = ultrasonic.MeasureInCentimeters();
-	Serial.println("The distance to obstacles in front is: ");
 	Serial.print(RangeInInches);//0~157 inches
 	Serial.println(" inch");
+	delay(250)
+
+	RangeInCentimeters = ultrasonic.MeasureInCentimeters(); // two measurements should keep an interval
 	Serial.print(RangeInCentimeters);//0~400cm
 	Serial.println(" cm");
-	delay(100);
+	delay(250);
 }


Update Pong.ino - solves Issue #2

Update Pong.ino - solves Issue #2

--- examples/Pong/Pong.ino
+++ examples/Pong/Pong.ino
@@ -214,7 +214,7 @@
 			tft.setCursor(40,40);
 			tft.println("You");
 			tft.setCursor(0,64);
-			tone(3, 110-330*(ball[0] < 64) == player), 600);
+			tone((3, 110-330*(ball[0] < 64) == player), 600);
 			tft.print((1 + (ball[0] < 64) == player) ? "  won!" : "lost :(");
 			while(!HackBoy.getStartKey());
 			showMenu();


add rotation

add rotation

--- Fast_LEDs_combo_w__Accel_code/Fast_LEDs_combo_w__Accel_code.ino
+++ Fast_LEDs_combo_w__Accel_code/Fast_LEDs_combo_w__Accel_code.ino
@@ -102,7 +102,7 @@
 //    //Stick.Interval = 20;
 //    Stick.Color1=Stick.Color(x*32,y*32, z*32);
 //      Stick.Update();
-        juggle();
+        rgb(x*64, y*64, z*64);
     }
 }

@@ -176,6 +176,13 @@
   }
 }

+void rgb(uint8_t r, uint8_t g, uint8_t b) {
+  for (int i = 0; i < NUM_LEDS; i++)
+  {
+    leds[i] = CRGB (r, g, b);
+  }
+}
+
 void juggle() {
 //  // eight colored dots, weaving in and out of sync with each other
 //  fadeToBlackBy( leds, NUM_LEDS, 20);


big stuff

big stuff

--- coni/arduino/main/master/multi_master.ino
+++ coni/arduino/main/master/multi_master.ino
@@ -119,8 +119,8 @@
           completo++;
           break;
         case 'E':
-          if (dataIn[0] > 360) { //vel E
-            dataOut = dataIn + 11500000;
+          if (dataIn > 360) { //vel E
+            dataOut[0] = dataIn + 11500000;
           }
           else { //abs E
             dataOut[0] = dataIn * (100800 / 360) + 20500000;


General stability fixes.

General stability fixes.

--- ardex/ardex.ino
+++ ardex/ardex.ino
@@ -3,9 +3,7 @@
 #include "config.h"

 const int info = 13;
-unsigned char state = INIT_STATE;1
-int adata, itmp;
-unsigned char data, tmp;
+static unsigned char state = INIT_STATE;
 volatile unsigned char sinfo = 0;

 #ifdef USE_INT0
@@ -21,6 +19,8 @@
 #endif // USE_INT1

 void i2c_rx(int nBytes) {
+  static int itmp;
+  static unsigned char tmp;
   sinfo |= 4;
   tmp = state;
   state = Wire.read();
@@ -50,6 +50,8 @@
 }

 void i2c_tx() {
+  static int adata;
+  static unsigned char tmp, data;
   Wire.write(sinfo);
   sinfo ^= sinfo;
   Wire.write(state);


umstellung auf Arduino Nano und ESP8266

umstellung auf Arduino Nano und ESP8266

--- ATtiny_Humidor_Monitoring/ATtiny_Humidor_Monitoring.ino
+++ ATtiny_Humidor_Monitoring/ATtiny_Humidor_Monitoring.ino
@@ -71,19 +71,19 @@
 //digital Output
 int out1 = 12;

-//DHT lib
+//DHT Lib
 int dhtPin = 4;
 #include "DHT.h"
 DHT dht;

 //Pausen zwischen den Messungen in Millisekunden
-unsigned long stime = 1800000; // Zeit zwischen den Sendezeiten
-unsigned long mtime = 900000; // Zeit zwischen den Messungen
+unsigned long stime = 1800000L; // Zeit zwischen den Sendezeiten
+unsigned long mtime = 900000L; // Zeit zwischen den Messungen

 boolean fanOn; // Boolean Feld fuer den Status vom Luefter.

 void setup() {
-  //Serial.begin(115200);
+  Serial.begin(115200);
   // VirtualWire Initialise the IO and ISR

   vw_set_ptt_inverted(false); // Required for RF Link module
@@ -95,30 +95,29 @@
   fanOn = false;

   dht.setup(dhtPin);
-  //Serial.println(F("setup end"));
-
+  Serial.println(F("setup end"));
 }

 unsigned long task1, task2 = 0;
 void loop() {
   unsigned long currmillis = millis();

-  //falls der Luefter laeuft pruefe alle 5 Sekunden die Werte
+  //falls der Luefter laeuft pruefe alle 15 Sekunden die Werte
   if (fanOn) {
     if ((unsigned long)(currmillis - task2) >= 15000) {
       byte i;
-      //Serial.println(F("check if hum"));
+      Serial.println(F("check if hum"));
       if ((float)(get_hum() <= 65.0 || get_hum() <= 70.0)) {
         if (!fanOn) {
           //oeffne die Belueftung und starte den Luefter
-          //Serial.println(F("fan ON"));
+          Serial.println(F("fan ON"));
           digitalWrite(out1, HIGH);
           fanOn = true;
         }
       } else {
         if (fanOn) {
           // switch fan1 off und schliesse den Schlitz
-          //Serial.println(F("fan off"));
+          Serial.println(F("fan off"));
           digitalWrite(out1, LOW);
           fanOn = false;
         }
@@ -129,7 +128,7 @@

   // Wenn die Zeit (worktime) kleiner als die Vergangene Zeit ist, Sende die Messdaten.
   if ((unsigned long)(currmillis - task1) >= stime || (currmillis == 1000)) {
-    //Serial.println(F("check DHT22"));
+    Serial.println(F("check DHT22"));
     TransmitData(get_temp(), get_hum());
     task1 = millis();
   }
@@ -137,18 +136,18 @@
   // checke die Luftfeuchtigkeit und wenn zu niedrig schalte Luefter ein.
   if ((unsigned long)(currmillis - task2) >= mtime) {
     byte i;
-    //Serial.println(F("check if hum"));
+    Serial.println(F("check if hum"));
     if ((float)(get_hum() <= 65.0 || get_hum() <= 70.0)) {
       if (!fanOn) {
         //oeffne die Belueftung und starte den Luefter
-        //Serial.println(F("Switch fan on"));
+        Serial.println(F("Switch fan on"));
         digitalWrite(out1, HIGH);
         fanOn = true;
       }
     } else {
       if (fanOn) {
         // switch fan1 off und schliesse den Schlitz
-        //Serial.println(F("Switch fan off"));
+        Serial.println(F("Switch fan off"));
         digitalWrite(out1, LOW);
         fanOn = false;
       }
@@ -172,7 +171,6 @@
    * Erstelle eine Datenstruktur und
    * sende es danach mit einer simplen
    * Pruefsumme an den Empfaenger
-   *
   */

   struct wData_STRUCT {


Removed BootSetTest

Removed BootSetTest

--- Code/Examples/Sandbox/Utils/BoolSetTest/BoolSetTest.ino
+++ Code/Examples/Sandbox/Utils/BoolSetTest/BoolSetTest.ino
@@ -1,52 +0,0 @@
-/**
- * This file is part of the Meshwork project.
- *
- * Copyright (C) 2013, Sinisha Djukic
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General
- * Public License along with this library; if not, write to the
- * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
- * Boston, MA  02111-1307  USA
- */
-#include <stdio.h>
-#include <stdlib.h>
-#include "Cosa/Trace.hh"
-#include "Cosa/Types.h"
-#include "Cosa/IOStream.hh"
-#include "Cosa/IOStream/Driver/UART.hh"
-#include "Cosa/Watchdog.hh"
-#include "Cosa/RTC.hh"
-#include "Cosa/Wireless.hh"
-#include <Meshwork.h>
-#include "Utils/BoolSet.h"
-
-void setup()
-{
-  uart.begin(9600);
-  trace.begin(&uart, PSTR("BoolSetTest: started"));
-  Watchdog::begin();
-  RTC::begin();
-}
-
-void loop()
-{
-	static int const MAX = 10;
-	BoolSet<MAX> bs(false);
-	bs.set(0, true);
-	bs.set(1, true);
-	bs.set(7, true);
-	bs.set(8, true);
-	bs.set(9, true);
-	for ( int i = 0; i < MAX; i ++ )
-		trace << bs.get(i) << PSTR("\n");
-}


add low-power survival strategy

add low-power survival strategy

--- examples/RF12/radioBlip2/radioBlip2.ino
+++ examples/RF12/radioBlip2/radioBlip2.ino
@@ -4,7 +4,8 @@
 #include <JeeLib.h>
 #include <avr/sleep.h>

-#define BLIP_ID 1  // set this to a unique ID to disambiguate multiple nodes
+#define BLIP_ID   2 // set this to a unique ID to disambiguate multiple nodes
+#define SEND_MODE 3 // set to 3 if fuses are e=06/h=DE/l=CE, else set to 2

 struct {
   long ping;  // 32-bit counter
@@ -15,15 +16,15 @@

 volatile bool adcDone;

-// this must be added since we're using the watchdog for low-power waiting
+// for low-noise/-power ADC readouts, we'll use ADC completion interrupts
+ISR(ADC_vect) { adcDone = true; }
+
+// this must be defined since we're using the watchdog for low-power waiting
 ISR(WDT_vect) { Sleepy::watchdogEvent(); }
-
-// for low-noise/-power ADC readouts, we'll use interrupts
-ISR(ADC_vect) { adcDone = true; }

 static byte vccRead (byte count =4) {
   set_sleep_mode(SLEEP_MODE_ADC);
-  ADMUX = bit(REFS0) | 14; // use VCC and internal bandgap
+  ADMUX = bit(REFS0) | 14; // use VCC as AREF and internal bandgap as input
   bitSet(ADCSRA, ADIE);
   while (count-- > 0) {
     adcDone = false;
@@ -48,25 +49,51 @@
   rf12_initialize(17, RF12_868MHZ, 5);
   // see http://tools.jeelabs.org/rfm12b
   rf12_control(0xC040); // set low-battery level to 2.2V i.s.o. 3.1V
+  rf12_sleep(RF12_SLEEP);
+
   payload.id = BLIP_ID;
 }

-void loop() {
-  payload.vcc1 = vccRead();
-
+static byte sendPayload () {
   ++payload.ping;

-  while (!rf12_canSend())
-    rf12_recvDone();
+  rf12_sleep(RF12_WAKEUP);
+  rf12_sendStart(0, &payload, sizeof payload);
+  rf12_sendWait(SEND_MODE);
+  rf12_sleep(RF12_SLEEP);
+}
+
+// This code tries to implement a good survival strategy: when power is low,
+// don't transmit - when power is even lower, don't read out the VCC level.
+//
+// With a 100 µF cap, normal packet sends can cause VCC to drop by some 0.6V,
+// hence the choices below: sending at >= 2.8V should be ok most of the time.
+
+#define VCC_OK    90  // >= 2.8V - enough power for normal 1-minute sends
+#define VCC_LOW   80  // >= 2.6V - sleep for 1 minute, then try again
+#define VCC_DOZE  60  // >= 2.2V - sleep for 5 minutes, then try again
+                      //  < 2.2V - sleep for 60 minutes, then try again
+#define VCC_SLEEP_MINS(x) ((x) >= VCC_LOW ? 1 : (x) >= VCC_DOZE ? 5 : 60)
+
+// Reasoning is that when we're about to try sending and find out that VCC
+// is far too low, then let's just send anyway, as one final sign of life.
+
+#define VCC_FINAL 70  // <= 2.4V - send one last packet, our swan song
+
+void loop() {
+  byte vcc = payload.vcc1 = vccRead();

-  rf12_sendStart(0, &payload, sizeof payload);
-  // set the sync mode to 2 if the fuses are still the Arduino default
-  // mode 3 (full powerdown) can only be used with 258 CK startup fuses
-  rf12_sendWait(2);
+  if (vcc <= VCC_FINAL) { // hopeless, maybe we can get one last packet out
+    sendPayload();
+    vcc = payload.vcc2 = 1; // don't even try reading VCC after this send
+  }

-  payload.vcc2 = vccRead();
-
-  rf12_sleep(RF12_SLEEP);
-  Sleepy::loseSomeTime(60000);
-  rf12_sleep(RF12_WAKEUP);
+  if (vcc >= VCC_OK) { // enough energy for normal operation
+    sendPayload();
+    vcc = payload.vcc2 = vccRead(); // measure and remember the VCC drop
+  }
+
+  byte minutes = VCC_SLEEP_MINS(vcc);
+  while (minutes-- > 0)
+    Sleepy::loseSomeTime(60000);
 }


updated parallel out 2

updated parallel out 2

--- proj/parallel_out_test_2/parallel_out_test_2.ino
+++ proj/parallel_out_test_2/parallel_out_test_2.ino
@@ -11,26 +11,6 @@
 // WS2811_PORTD: 25,26,27,28,14,15,29,11
 //

-const TProgmemPalette16 WhiteBlack_p PROGMEM = {
-  CRGB::Red,
-  CRGB::Blue,
-  CRGB::Orange,
-  CRGB::Purple,
-  CRGB::Yellow,
-  CRGB::Green,
-  CRGB::White,
-  CRGB::Pink,
-  CRGB::White,
-  CRGB::Black,
-  CRGB::Black,
-  CRGB::Black,
-  CRGB::White,
-  CRGB::Black,
-  CRGB::Black,
-  CRGB::Black,
-};
-
-
 void setup() {
   // LEDS.addLeds<WS2811_PORTA,NUM_STRIPS>(leds, NUM_LEDS_PER_STRIP);
   // LEDS.addLeds<WS2811_PORTB,NUM_STRIPS>(leds, NUM_LEDS_PER_STRIP);
@@ -43,9 +23,9 @@

 void loop() {

-  for (uint8_t strip = 0; strip < NUM_STRIPS; strip++) {
-    for (uint8_t ll = 0; ll < NUM_LED; ll++) {
-      leds[strip * NUM_LED + ll] = CHSV(strip*2*16, 192, 255);
+  for (int i = 0; i < NUM_STRIPS; i++) {
+    for (int j = 0; j < NUM_LED; j++) {
+      leds[(i * NUM_LED) + j] = CHSV((32 * i), 192, 255);
     }
   }


Integratino- analog output set.

Integratino- analog output set.

--- Medium-Projects/LeakyIntegratino/LeakyIntegratino.ino
+++ Medium-Projects/LeakyIntegratino/LeakyIntegratino.ino
@@ -6,7 +6,7 @@
 double Vm     = 0.0; // membrane potential
 double Vth    = 1.0; // threshold potential
 double Vr     = 0.0; // resetting potential
-double g      = 1.0; //
+double g      = 2.0; //
 int inCurrent = 0;   // input current

 double PulseAmplitude = 5.0; // amplitude of the button pulse
@@ -27,8 +27,11 @@
 // Temperature sensor
 int tempPin = 1;        // Analog temperature sensor pin
 int reading;            // Reading from sensor
-float NersntEffectCons = 0.05;
+float NersntEffectCons = 0.01;

+
+// Analogical output
+int outputPin = 6;

 // Setting up the serial port
@@ -44,6 +47,7 @@
   pinMode(readInterrupt, INPUT);
   pinMode(ledPin_inputSPK, OUTPUT);
   pinMode(ledPin_spikesign, OUTPUT);
+  pinMode(outputPin, OUTPUT);
 }

 void loop()
@@ -64,7 +68,7 @@
   digitalWrite(ledPin_inputSPK, inCurrent);

   // Updating the input current
-  double I = .3 + inCurrent*PulseAmplitude;
+  double I = .2 + inCurrent*PulseAmplitude;

   // Updating the membrane potential
   if ( Not_Resting )
@@ -101,6 +105,9 @@
   Serial.print(" ");
   Serial.println(Vm, 8);

+  // Updating the analogical output (using PWM)
+  analogWrite(outputPin, min(max(20,Vm*250),240) );
+
   delay(30);
 }


Fixed people's complaints

Fixed people's complaints

--- installation/examples/Debug_uSpeech/Debug_uSpeech.ino
+++ installation/examples/Debug_uSpeech/Debug_uSpeech.ino
@@ -1,207 +1,41 @@
 #include <uspeech.h>
 signal voice(A0);
 char option = 0;
-uint32_t power(uint32_t base, uint32_t exp);
-
-void setup()
-{
-#if 0
-    int minVolume;  /*!< This is the highest audio power that should be considered ready */
-    int fconstant;  /*!< This is the threshold for /f/, configure it yourself */
-    int econstant;  /*!< This is the threshold for /ee/, /i/, configure it yourself */
-    int aconstant;  /*!< This is the threshold for /a/ /o/ /r/ /l/, configure it yourself */
-    int vconstant;  /*!< This is the threshold for /z/ /v/ /w/, configure it yourself */
-    int shconstant; /*!< This is the threshold for /sh/ /ch/, above this everything else is regarded as /s/ */
-    bool f_enabled; /*!< Set this to false if you do not want to detect /f/s */
-    int amplificationFactor; /*!<Amplification factor: Adjust as you need*/
-#endif
-    analogReference(EXTERNAL);
-
-    voice.f_enabled = true;
-    voice.fconstant = 240;
-    voice.econstant = 2; //3; //1 2;
-    voice.aconstant = 4; //5; //2 4;
-    voice.vconstant = 6; //7; //3 6;
-    voice.shconstant = 8; //4;
-    voice.amplificationFactor = 10;
-    voice.micPowerThreshold = 80;
-    voice.scale = 8;
-    Serial.begin(115200);
-
-#if 0
-    while (1) {
-        uint16_t sig = analogRead(A0);
-	Serial.println(sig);
-	delay(100);
-    }
-#endif
-
-    Serial.println(F("Calibrating"));
-    voice.calibrate();
-    Serial.print(F("Calibrated at "));
-    Serial.println(voice.calib);
-    Serial.println(F("Ready"));
+void setup(){
+  voice.calibrate();
+  voice.f_enabled = true;
+  Serial.begin(9600);
 }
-
-uint16_t lastMicPower=0;
-char lastPhoneme = ' ';;
-uint16_t lastCoeff=0;
-uint16_t lastPower=0;
-uint32_t lastChange = 0;
-uint32_t startUsec = 0;
-
-uint8_t col=0;
-
-char buf[80];
-
-struct history_s {
-    int micPower;
-    int coeff;
-    char phoneme;
-    char f_phoneme;
-    uint32_t usecs;
-} history[80];
-
-uint32_t power(uint32_t base, uint32_t ex)
-{
-    if (ex == 0)
-	return 1;
-    else if (ex % 2)
-	return base * power(base, ex - 1);
-    else {
-	int temp = power(base, ex / 2);
-	return temp * temp;
-    }
+void loop(){
+  //voice.sample();
+
+  char c=voice.getPhoneme();
+  if(option==0){
+    Serial.println("uSpeech debug tool--------");
+    Serial.println(" Press 'a' if you wish to calibrate/check the f algorithm");
+    Serial.println(" Press 'b' if you wish to calibrate/check the getPhoneme");
+    Serial.println(" Press 'c' if you wish to calibrate/check the volume of your microphone");
+    Serial.println(" Press 'd' if you wish to calibrate/check the coeff");
+
+    option = 1;
+  }
+  if(option==1){
+   if (Serial.available() > 0) {
+                // read the incoming byte:
+                option = Serial.read();
+   }
+  }
+  if(option=='a'){
+    Serial.println(voice.micPower);
+  }
+  if(option=='b'){
+    Serial.println(c);
+  }
+  if(option=='c'){
+    Serial.println(voice.power());
+  }
+  if(option=='d'){
+  	Serial.println(voice.testCoeff);
+  }
+
 }
-
-void pad(uint32_t value, uint8_t places)
-{
-    uint32_t padValue = power(10, places);
-
-    while (value < padValue) {
-        Serial.print(' ');
-	padValue /= 10;
-    }
-    Serial.print(value);
-}
-
-void loop()
-{
-    char phoneme = voice.getPhoneme();
-    if (option==0) {
-	Serial.println(F("uSpeech debug tool--------"));
-	Serial.println(F(" Press 'f' if you wish to calibrate/check the f algorithm (micPower)"));
-	Serial.println(F(" Press 'p' if you wish to calibrate/check the getPhoneme"));
-	Serial.println(F(" Press 'v' if you wish to calibrate/check the volume of your microphone"));
-	Serial.println(F(" Press 'c' if you wish to calibrate/check the coeff"));
-	option = 1;
-    }
-    if (Serial.available() > 0) {
-	option = Serial.read();
-    }
-    switch (option) {
-    case 'f': {
-	uint16_t micPower = voice.micPower;
-	if (micPower != lastMicPower) {
-	    Serial.print(F("micPower: "));
-	    Serial.println(micPower);
-	    lastMicPower = micPower;
-	}
-	}
-	break;
-    case 'p': {
-	if (phoneme != lastPhoneme || phoneme != ' ') {
-	    if (col == 0) {
-		startUsec = micros();
-	    }
-	    lastPhoneme = phoneme;
-	    buf[col] = phoneme;
-	    history[col].phoneme = phoneme;
-	    history[col].f_phoneme = voice.phoneme;
-	    history[col].coeff = voice.testCoeff;
-	    history[col].micPower = voice.micPower;
-	    history[col].usecs = micros() - startUsec;
-	    startUsec = micros();
-	    if (++col >= sizeof(buf)-1) {
-	        buf[col] = 0;
-		Serial.println(F("phonemes"));
-		for (uint8_t ind=0; ind<col; ind++) {
-		    Serial.print(F("    "));
-		    pad(history[ind].usecs,5);
-		    Serial.print(F(": '"));
-		    Serial.print(history[ind].phoneme);
-		    Serial.print('\'');
-		    Serial.print(F(" ("));
-		    Serial.print(history[ind].coeff);
-		    Serial.print(',');
-		    Serial.print(history[ind].micPower);
-		    Serial.println(')');
-		}
-		Serial.print(F("phoneme sequence: \""));
-		Serial.print(buf);
-		Serial.println('"');
-	        col = 0;
-	    }
-	    lastChange = millis();
-	}
-	if (col && ((millis() - lastChange) > 50)) {
-	    buf[col] = 0;
-	    Serial.println(F("phonemes"));
-	    for (uint8_t ind=0; ind<col; ind++) {
-		Serial.print(F("    "));
-		pad(history[ind].usecs,5);
-		//Serial.print(history[ind].usecs);
-		Serial.print(F(": '"));
-		Serial.print(history[ind].phoneme);
-		Serial.print('\'');
-		Serial.print(F(" ("));
-		Serial.print(history[ind].coeff);
-		Serial.print(',');
-		Serial.print(history[ind].micPower);
-		Serial.print(')');
-		if (history[ind].phoneme == 'f') {
-		    Serial.print(" '");
-		    Serial.print(history[ind].f_phoneme);
-		    Serial.println('\'');
-		} else {
-		    Serial.println();
-		}
-	    }
-	    col = 0;
-	    Serial.print(F("phoneme sequence: \""));
-	    Serial.print(buf);
-	    Serial.println('"');
-	    Serial.println(F("-----------------------------"));
-	}
-	}
-	break;
-    case 'v': {
-	uint16_t power = voice.power();
-	if (power != lastPower) {
-	    Serial.print(F("power:"));
-	    Serial.println(power);
-	    lastPower = power;
-	}
-	}
-	break;
-    case 'c': {
-	uint16_t coeff = voice.testCoeff;
-	if (coeff != lastCoeff) {
-	    Serial.print(F("coeff: "));
-	    Serial.println(coeff);
-	    lastCoeff = coeff;
-	}
-	}
-	break;
-    case 1:
-	break;
-    default:
-	option = 0;
-	if (col) {
-	    Serial.println();
-	    col = 0;
-	}
-	break;
-    }
-
-}


Add publishers for encoder counts. (#51)

--- Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
+++ Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
@@ -25,6 +25,7 @@
 #include <LIS3MDL.h>

 // Other includes
+#include <limits.h>
 #include <Timer.h>
 #include "RosParamHelper.h"

@@ -36,6 +37,7 @@
 #include <victoria_debug_msgs/TeensyDebug.h>
 #include <victoria_nav_msgs/Odom2DRaw.h>
 #include <victoria_sensor_msgs/DistanceDisplacement1D.h>
+#include <victoria_sensor_msgs/EncoderCount.h>
 #include <victoria_sensor_msgs/IMURaw.h>

 // Teensy pin definitions
@@ -136,6 +138,12 @@
 ros::Publisher ros_bumper_left_pub("bumper_left", &ros_bumper_left_msg);
 ros::Publisher ros_bumper_right_pub("bumper_right", &ros_bumper_right_msg);

+// Encoder publishers
+victoria_sensor_msgs::EncoderCount ros_encoder_left_msg;
+victoria_sensor_msgs::EncoderCount ros_encoder_right_msg;
+ros::Publisher ros_encoder_left_pub("encoder_left", &ros_encoder_left_msg);
+ros::Publisher ros_encoder_right_pub("encoder_right", &ros_encoder_right_msg);
+
 // Position of robot
 geometry_msgs::Pose2D pose;

@@ -157,6 +165,8 @@
   ros_nh.advertise(ros_raw_imu_pub);
   ros_nh.advertise(ros_bumper_left_pub);
   ros_nh.advertise(ros_bumper_right_pub);
+  ros_nh.advertise(ros_encoder_left_pub);
+  ros_nh.advertise(ros_encoder_right_pub);
   ros_nh.advertise(ros_teensy_debug_pub);

   // Register ros subscribers
@@ -184,6 +194,9 @@

   int publish_bumper_info_freq_hz =
     ros_param_helper.getParam("publish_bumper_info_freq_hz", 10);
+
+  int publish_encoder_info_freq_hz =
+    ros_param_helper.getParam("publish_encoder_info_freq_hz", 10);

   int publish_teensy_debug_info_freq_hz =
     ros_param_helper.getParam("publish_teensy_debug_info_freq_hz", 1);
@@ -244,6 +257,7 @@
   setupTimerCallback(publish_raw_odom_freq_hz, doPublishRawOdom);
   setupTimerCallback(publish_raw_imu_freq_hz, doPublishRawImu);
   setupTimerCallback(publish_bumper_info_freq_hz, doPublishBumpers);
+  setupTimerCallback(publish_encoder_info_freq_hz, doPublishEncoders);
   setupTimerCallback(publish_teensy_debug_info_freq_hz, doTeensyDebug);
   setupTimerCallback(BLINK_FREQ_HZ, doBlink);

@@ -252,6 +266,8 @@
   ros_raw_odom_msg.child_frame_id = "/base_link";
   ros_bumper_left_msg.header.frame_id = "/bumper_left";
   ros_bumper_right_msg.header.frame_id = "/bumper_right";
+  ros_encoder_left_msg.header.frame_id = "/encoder_left";
+  ros_encoder_right_msg.header.frame_id = "/encoder_right";
   last_cmd_vel_time = current_time;
   cmd_vel_timeout_exceeded = false;
   last_encoder_read_time = current_time;
@@ -584,6 +600,28 @@
   return distance_sample_lower + (intermediatePercentage * (distance_sample_upper - distance_sample_lower));
 }

+/**
+ * Publish encoder data to ros.
+ */
+void doPublishEncoders(void) {
+  ros::Time current_time = ros_nh.now();
+  long encoder_left_count = encoder_left.read();
+  long encoder_right_count = encoder_right.read();
+
+  ros_encoder_left_msg.header.stamp = current_time;
+  ros_encoder_left_msg.count = encoder_left_count;
+  ros_encoder_left_msg.min_value = LONG_MIN;
+  ros_encoder_left_msg.max_value = LONG_MAX;
+
+  ros_encoder_right_msg.header.stamp = current_time;
+  ros_encoder_right_msg.count = encoder_right_count;
+  ros_encoder_right_msg.min_value = LONG_MIN;
+  ros_encoder_right_msg.max_value = LONG_MAX;
+
+  ros_encoder_left_pub.publish(&ros_encoder_left_msg);
+  ros_encoder_right_pub.publish(&ros_encoder_right_msg);
+}
+
 /*
  * Sets the speed for the motors. Values are expected
  * to be between -1 and 1. Values outside this range


Changed the WebClient code so it works, now using Serial and Serial1 for debug

--- examples/WebClient/WebClient.ino
+++ examples/WebClient/WebClient.ino
@@ -16,6 +16,8 @@
 #include <SoftwareSerial.h>
 #include <SIM900.h>

+#define debug Serial1
+
 // PIN Number
 #define PINNUMBER ""

@@ -32,14 +34,15 @@

 // URL, path & port (for example: arduino.cc)
 char server[] = "arduino.cc";
-char path[] = "/";
+char path[] = "/asciilogo.txt";
 int port = 80; // 80 for HTTP

 void setup()
 {
   // initialize serial communications
-  Serial.begin(9600);
-  Serial.println("Starting Arduino web client.");
+  debug.begin(115200);
+  Serial.begin(57600); // must set the baudrate to the modem and initialize the serial port to the modem
+  debug.println("Starting Arduino web client.");
   // connection state
   boolean notConnected = true;

@@ -53,17 +56,17 @@
       notConnected = false;
     else
     {
-      Serial.println("Not connected");
+      debugln("Not connected");
       delay(1000);
     }
   }

-  Serial.println("connecting...");
+  debugln("connecting...");

   // if you get a connection, report back via serial:
   if (client.connect(server, port))
   {
-    Serial.println("connected");
+    debugln("connected");
     // Make a HTTP request:
     client.beginWrite();
     client.print("GET ");
@@ -75,7 +78,7 @@
   else
   {
     // if you didn't get a connection to the server:
-    Serial.println("connection failed");
+    debugln("connection failed");
   }
 }

@@ -86,14 +89,14 @@
   if (client.available())
   {
     char c = client.read();
-    Serial.print(c);
+    debug(c);
   }

   // if the server's disconnected, stop the client:
   if (!client.available() && !client.connected())
   {
-    Serial.println();
-    Serial.println("disconnecting.");
+    debugln();
+    debugln("disconnecting.");
     client.stop();

     // do nothing forevermore:


Remove misleading comments

Remove misleading comments

--- examples/Widgets/Timer/Timer.ino
+++ examples/Widgets/Timer/Timer.ino
@@ -30,12 +30,12 @@
 #include <Ethernet.h>
 #include <BlynkSimpleEthernet.h> // This part is for Ethernet stuff

-char auth[] = "YourAuthToken"; // Put your Auth Token here. (see Step 3 above)
+char auth[] = "YourAuthToken";

 void setup()
 {
   Serial.begin(9600); // See the connection status in Serial Monitor
-  Blynk.begin(auth);  // Here your Arduino connects to the Blynk Cloud.
+  Blynk.begin(auth);
 }

 BLYNK_WRITE(V5)


updated rotation check logic

updated rotation check logic

back to where it was before.

--- Exhibit_MomentumTable.ino
+++ Exhibit_MomentumTable.ino
@@ -14,14 +14,14 @@
 //////
 #define DESIREDRPM_TABLE    60      //desired RPM on output wheel
 //#define DESIREDRPM_MOTOR    600     //desired motor RPM (this may be superfulous)
-#define DISCSLIPCOUNT       250     //How long alarm cond before alarm signal
+#define DISCSLIPCOUNT       50    //How long alarm cond before alarm signal
 #define LOCKEDDISCRPM       30     //RPM to consider as "disc stopped"
 #define ROTATIONVARIANCE    2      //Variance in RPM before alarm condition

 #define LOCKEDDISCRPM       10      //RPM to consider as "disc stopped"
-#define ROTATIONVARIANCE    50      //Variance in RPM before alarm condition
+#define ROTATIONVARIANCE    12	      //Variance in RPM before alarm condition
 //#define TRANSMISSIONRATIO   10      //Tranmission drive ratio n:1
-#define NUMBEROFRESTARTS    5      //#of restarts attempted after stopped state
+#define NUMBEROFRESTARTS    3      //#of restarts attempted after stopped state
 #define STARTTIME           10000   //Expected ramp up time, in MS
 #define STOPTIME            10000   //Expected ramp down time, in MS
  /////////
@@ -77,7 +77,7 @@
 if  (allStopVar == 0){
     calculateRPM();
     discSlipCheck();
-   // lockedRotorCheck();
+    lockedRotorCheck();
 }
     //now = millis();
     //MQTT Connection Check
@@ -109,23 +109,23 @@
   }

 void motionControlStart(){
-    Serial.println("Motor Control Start");
     if (restartCount < NUMBEROFRESTARTS){
         digitalWrite(STARTRELAYPIN, HIGH); // enable start relay if not above fail counter
-        delay(5000); // wait for 2 second for a rotation
+        delay(4000); // wait for 4 second for a rotation
+		    Serial.println("Motor Control Start");
+
         if (pulseCount == 0){               // if no rotation detected in interrupt
             digitalWrite(STARTRELAYPIN, LOW); // turn off motor becuase of no rotation
 			Serial.println("No rotation detected -- attempting restart");
             restartCount++;
-            delay (3000); // delay 3 seconds before attempting restart
+            delay (STOPTIME); // delay 10 seconds before attempting restart
             pulseCount = 0; // reset pulse count
             motionControlStart();
             }
-        if (pulseCount > 1){
+        if (pulseCount >= 1){
         Serial.println("motion started, system running");
-		delay(3000); 	// wait 3 seconds for disc to come up to fast enough speed
+		delay(STARTTIME); 	// wait 10(STARTTIME) seconds for disc to come up to fast enough speed
 						// to not trip locked rotor functiion
-		pulseCount = 0;
         restartCount = 0; // set restart counter to 0, since we're started
         allStopVar = 0; // Set allstop condition to off
         }
@@ -151,24 +151,29 @@
 }

 void discSlipCheck(){
-    if (rpm < (DESIREDRPM_TABLE - ROTATIONVARIANCE)){
+    if (rpm < ((DESIREDRPM_TABLE - ROTATIONVARIANCE) && (allStopVar == 0))){
         discSlipPrecond++;
         }
     else
-        if (discSlipPrecond > 0){
+        if (discSlipPrecond > 0 && allStopVar == 0){
         discSlipPrecond--;
         }
     if (discSlipPrecond > DISCSLIPCOUNT){
-    client.publish(TOPIC_T, "Error: - Continuious Disc Slip Detected");
+	Serial.println("Continious disc slip detected");
+    client.publish(TOPIC_T, "Error: - Continuious Disc Slip Detected");
+	discSlipPrecond = 0;
     }
 }

 void lockedRotorCheck(){
     if (rpm <= LOCKEDDISCRPM){
+		Serial.println("Locked rotor. attempting restart");
         digitalWrite(STARTRELAYPIN, LOW); // immediately shut down if RPM lowByte
-        }
-        client.publish(TOPIC_T, "CritErr: Disc rotation is locked, attempting restart");
+        client.publish(TOPIC_T, "CritErr: Disc rotation is locked, attempting restart");
+		delay(STOPTIME);
+		motionControlStart();
+		}
 }

 void allStop(){


implemented button handling from UART proxy

--- ksp-gegi-microusb/ksp-gegi-microusb.ino
+++ ksp-gegi-microusb/ksp-gegi-microusb.ino
@@ -3,6 +3,8 @@
 #include <Wire.h>
 // https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads
 #include <LiquidCrystal_I2C.h> // Using version 1.2.1
+// https://github.com/MHeironimus/ArduinoJoystickLibrary
+#include <Joystick.h>

 // IDE: Arduino/Genuino Micro

@@ -32,6 +34,9 @@
   analogOutPin(1,10)    // electrical power
 };

+// Stage/Abort status (on=stage, off=abort
+uint8_t stageabort = 1;
+
 // Set the pins on the I2C chip used for LCD connections:
 //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
 LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
@@ -53,6 +58,8 @@
   lcd.print("KSP-Gegi");
   lcd.setCursor(0,1);
   lcd.print("Ready for action");
+  // joystick setup
+  Joystick.begin(false);	// don't do auto send state
   // request status update
   Serial.println("I");
 }
@@ -97,6 +104,36 @@
   }
 }

+// called after UART slave reports button press/release
+void handleSlaveButton(const uint8_t id, const uint8_t state) {
+	// handle stage switch
+	uint8_t buttonId = 0x80;
+	switch (id) {
+		case 4:
+			buttonId = 5;
+			break;
+		case 5:
+			buttonId = 4;
+			break;
+		case 6:
+			buttonId = 2;
+			break;
+		case 7:
+			buttonId = 3;
+			break;
+		case 8:
+			buttonId = stageabort ? 1 : 0;
+			break;
+		case 9:
+			stageabort = state;	// on=abort, off=stage
+			break;
+	}
+//Serial.print("id,state,buttonid,stageabort="); Serial.print(id); Serial.write(' '); Serial.print(state); Serial.write(' '); Serial.print(buttonId); Serial.write(' '); Serial.println(stageabort);
+	if (buttonId < 0x80) {
+		Joystick.setButton(buttonId,state);
+	}
+}
+
 // pass data from USB host (PC) to UART
 // - handle own devices (consume this data)
 // - pass everything else to mini slave
@@ -124,13 +161,21 @@
   while (Serial1.available()) {
 		c = Serial1.read();
 		Serial.write(c);
+		if (c == 'D') {
+			const uint8_t id = Serial1.parseInt();  // skip '='
+			const uint8_t state = Serial1.parseInt(); // skip newline
+			Serial.print(id);
+			Serial.write('=');
+			Serial.println(state);
+			handleSlaveButton(id,state);
+		}
 	}
 }

 void loop() {
   checkSerialInputUSBtoUART();
   checkSerialInputUARTtoUSB();
-  // send joystick state
+  Joystick.sendState();
   delay(200);
 }


good comments are good

good comments are good

--- PushButton/PushButton.ino
+++ PushButton/PushButton.ino
@@ -22,19 +22,18 @@

 // loop forever
 void loop() {
-  buttonState = digitalRead(buttonPin);  // get button state
+  buttonState = digitalRead(buttonPin);   // get button state
   if (buttonState == HIGH) {
-    digitalWrite(ledPin, HIGH);     // button pressed, turn on led
+    digitalWrite(ledPin, HIGH);           // button pressed, turn on led
   }
   else if (buttonState == LOW) {
-    digitalWrite(ledPin, LOW);           // button released, turn off led
+    digitalWrite(ledPin, LOW);            // button released, turn off led
   }

-
-  ledState = digitalRead(ledPin);
+  ledState = digitalRead(ledPin);         // get led state

   if (ledState != oldState) {
-    Serial.println(ledState);
+    Serial.println(ledState);             // print out led state only if it changed
     oldState = ledState;
   }
 }


Added comments

Added comments

--- SenseGrain/SenseGrain.ino
+++ SenseGrain/SenseGrain.ino
@@ -115,7 +115,7 @@
 //Main Program Loop -----------------------------------------------------
 void loop() {

-  if(masterSwitch==0){
+  if(masterSwitch==0){//timer setups

     //Now put the system to sleep
     if (f_wdt==1) {  // wait for timed out watchdog / flag is set when a watchdog timeout occurs
@@ -131,7 +131,7 @@
     }
   }

-  if(masterSwitch==1){
+  if(masterSwitch==1){//interrupt setup

     transmit();
     sleep();


Header changes, code to detect cmd_vel timeout.

--- Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
+++ Arduino/victoria_teensy_ros_node/victoria_teensy_ros_node.ino
@@ -2,16 +2,23 @@
  * Victoria Teensy ROS Node
  *
  * This code is the ROS node that executes on the Teensy processor
- * for the Victoria RoboMagellan team. It uses the rosserial
- * library to communicate with ROS. It uses Arduino and Teensy
- * libraries to interact with systems and circuits connected to the
- * Teensy processor. This code assumes that a Teensy 3.5 is used.
+ * for the Victoria RoboMagellan team.
+ *
+ * It uses the rosserial library to communicate with ROS. It uses
+ * Arduino and Teensy libraries to interact with systems and
+ * circuits connected to the Teensy processor. This code assumes
+ * that a Teensy 3.5 is used.
+ *
+ * https://github.com/victoriarobotics
+ *
  */

 // Teensy includes
 #define ENCODER_OPTIMIZE_INTERRUPTS
 #include <Encoder.h>  //
 #include <i2c_t3.h>
+#include <LSM6.h>
+#include <LIS3MDL.h>

 // ROS includes
 #include <ros.h>
@@ -30,21 +37,28 @@
 // TRex motor controller
 HardwareSerial trex = HardwareSerial();

+// Bumper sensors
+#define BUMPER_THRESHOLD 500  // Threshold that will indicate robot should stop
+unsigned int bumper_left_base;
+unsigned int bumper_right_base;
+
 // Motor encoders
 Encoder encoder_left(ENCODER_LEFT_PIN_1, ENCODER_LEFT_PIN_2);
 Encoder encoder_right(ENCODER_RIGHT_PIN_1, ENCODER_RIGHT_PIN_2);
 unsigned long encoder_left_pos;
 unsigned long encoder_right_pos;

-// Bumper sensors
-#define BUMPER_THRESHOLD 500  // Threshold that will indicate robot should stop
-unsigned int bumper_left_base;
-unsigned int bumper_right_base;
+// IMU and Magnetometer
+LSM6 imu;
+LIS3MDL mag;

 // ROS node handle
 ros::NodeHandle ros_nh;

 // ROS cmd_vel subscriber
+// Threshold, in nanoseconds, to wait for a cmd_vel message else take action
+// to stop robot activity
+#define CMD_VEL_TIMEOUT_THRESHOLD_NS 200000000
 void cmdVelCallback(const geometry_msgs::Twist& twist_msg);
 ros::Subscriber<geometry_msgs::Twist> ros_cmd_vel_sub("cmd_vel", cmdVelCallback);

@@ -70,6 +84,21 @@

   // Start serial port to TRex
   trex.begin(19200);
+
+  // Setup IMU and magenetometer that use I2C
+  if (imu.init()) {
+    imu.enableDefault();
+    // TODO: set timeout?
+  } else {
+    // TODO: How to handle error?
+  }
+
+  if (mag.init()) {
+    mag.enableDefault();
+    // TODO: set timeout?
+  } else {
+    // TODO: How to handle error?
+  }

   // Initialize ros node
   ros_nh.initNode();
@@ -102,6 +131,10 @@

   // If we have not received any cmd_vel messages for a while,
   // something is wrong, stop the robot.
+  if (current_time.toNsec() - last_cmd_vel_time.toNsec()
+        > CMD_VEL_TIMEOUT_THRESHOLD_NS) {
+    // TODO: Do something to stop the robot!
+  }

   // Read bumper sensors
   unsigned int new_bumper_left = analogRead(BUMPER_LEFT_PIN);


tone multiple now works

tone multiple now works

--- html/examples/02.Digital/toneMultiple/toneMultiple.ino
+++ html/examples/02.Digital/toneMultiple/toneMultiple.ino
@@ -1,14 +1,17 @@
+//  This example is Chibitronics Love to Code tested!
 /*
   Multiple tone player

  Plays multiple tones on multiple pins in sequence

  circuit:
- * 3 8-ohm speaker on digital pins 6, 7, and 11
+ * 3 8-ohm speaker on pins A0, A1, and A3

  created 8 March 2010
  by Tom Igoe
  based on a snippet from Greg Borenstein
+ modified 25 May 2016
+ by bunnie

 This example code is in the public domain.

@@ -21,22 +24,22 @@
 }

 void loop() {
-   // turn off tone function for pin 11:
-   noTone(11);
+  // turn off tone function for pin A3:
+  noTone(A3);
   // play a note on pin 6 for 200 ms:
-  tone(6, 440, 200);
+  tone(A0, 440, 200);
   delay(200);

-  // turn off tone function for pin 6:
-  noTone(6);
+  // turn off tone function for pin A0:
+  noTone(A0);
   // play a note on pin 7 for 500 ms:
-  tone(7, 494, 500);
+  tone(A1, 494, 500);
   delay(500);

-  // turn off tone function for pin 7:
-  noTone(7);
+  // turn off tone function for pin A1:
+  noTone(A1);
   // play a note on pin 11 for 500 ms:
-  tone(11, 523, 300);
+  tone(A3, 523, 300);
   delay(300);

 }


Added heartbeat response code.

Added heartbeat response code.

--- Alarm_Tone/Alarm_Tone.ino
+++ Alarm_Tone/Alarm_Tone.ino
@@ -115,16 +115,23 @@
   //Communications dictionary: '1' = alarm, '2' = heartbeat, '5' = reconfiguration
   //Reconfiguration protocol: "5 *mode*" ('5' signals that the next command is a reconfiguration, then a space, then the mode (0=sensor, 1=alarm, 2=query))
   //Todo: in laptop relay, program it to only forward the communications dictionary commands, need a way to signal groups of communications
-  //Todo: include fluctuation tolerance (e.g. 10 activations required before alarm)
-  //Todo: heartbeat communications
+  //DONE Todo: include fluctuation tolerance (e.g. 10 activations required before alarm)
+  //DONE Todo: heartbeat communications
   //Todo: communications on the serial interfaces may have varying length. Account for it
   //DONE Todo: slow down bluetooth send rate. It's too fast and will leave an alarm on forever.
+  //Todo: sort out serial communications into "protocols" and message grouping, so that serial data can be processed properly by the computer (e.g. start/stop characters, escape characters, etc.)
+  //rough thought: just surround each message with '|' to separate messages, and keep a bool indicating if the program is still inside a message or not. Allows to compare commands against a "mask" to avoid commands
+  //interferring with each other, blocking malformed commands, and such.
+  //Todo: signal binary data

   if (opMode == sensor) {
     waterReadings();
   }
   if (opMode == alarm) {
-    heartbeat();
+    int heartResult = heartbeat();
+    if (heartResult == 4 || heartResult / 10 == 4) {
+      speaker(heartDeath, sizeof(heartDeath));
+    }
   }

   if (Serial.available()) { //DO NOT allow mode reconfiguration via bluetooth. Security hazard.
@@ -135,8 +142,12 @@
       if (input == '5') {
         reconfiguration(); //Start reconfiguration code
       }
+
       else if (input == '2') { //a heartbeat came in, respond
-        heartbeat(true);
+        int heartResult = heartbeat(true);
+        if (heartResult == 4 || heartResult / 10 == 4) {
+          speaker(heartDeath, sizeof(heartDeath));
+        }
       }
       else if (input == '1') { //alarm has been rung
         speaker(alarmTone, sizeof(alarmTone));
@@ -238,7 +249,7 @@
   //if a heartbeat came in
   else if (sent) {
     delay(10); //this is needed
-
+
     //Assemble the returned value
     char num = Serial.read();
     int checkReturned = atoi((const char *) &num) * 10;


Added I2C init

Added I2C init

--- test/Arduino/Bosch_BNO055/Bosch_BNO055.ino
+++ test/Arduino/Bosch_BNO055/Bosch_BNO055.ino
@@ -15,6 +15,10 @@

 // For I2C
 #include <Wire.h>
+#define BNO055_ADDRESS_A (0x28)
+#define BNO055_ADDRESS_B (0x29)
+#define BNO055_ID        (0xA0)
+

 // MicroView OLED
@@ -55,7 +59,16 @@
 /*
  * \Brief: I2C init routine
 */
-s8 I2C_routine(void);
+s8 I2C_routine(void)
+{
+  /* Enable I2C */
+  Wire.begin();
+
+  // BNO055 clock stretches for 500us or more!
+#ifdef ESP8266
+  Wire.setClockStretchLimit(1000); // Allow for 1000us of clock stretching
+#endif
+}
 #endif
 /********************End of I2C APIs declarations***********************/
 /*  Brief : The delay routine


Trim whitespace

Trim whitespace

--- examples/compliance-otaa-halconfig/compliance-otaa-halconfig.ino
+++ examples/compliance-otaa-halconfig/compliance-otaa-halconfig.ino
@@ -244,7 +244,7 @@
 }

 void printTxend(ostime_t txend) {
-    Serial.print(F(", txend=")); Serial.print(txend);
+    Serial.print(F(", txend=")); Serial.print(txend);
 }

 void eventPrint(cEventQueue::eventnode_t &e) {


WIP ad-hoc

WIP ad-hoc

--- avoccado-adhoc-migration-wip/avoccado-adhoc-migration-wip.ino
+++ avoccado-adhoc-migration-wip/avoccado-adhoc-migration-wip.ino
@@ -1,16 +1,10 @@
 /*
- Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>
-
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- version 2 as published by the Free Software Foundation.
+ Avoccado
+ Open Source Haptic Input Device.
+ WIP Adhoc networking. No meshing.
+ Licensing information in the repository, see file LICENSE.
  */

-/**
- * Example using Dynamic Payloads
- *
- * This is an example of how to use payloads of a varying (dynamic) size.
- */

 #include <SPI.h>
 #include "nRF24L01.h"
@@ -25,7 +19,7 @@

 // sets the role of this unit in hardware.  Connect to GND to be the 'pong' receiver
 // Leave open to be the 'ping' transmitter
-const int role_pin = 7;
+const int role_pin = 1;

 //
 // Topology
@@ -66,14 +60,10 @@

 void setup(void)
 {
-
-  // set up the role pin
-  pinMode(role_pin, INPUT);
-  digitalWrite(role_pin,HIGH);
   delay(20); // Just to get a solid reading on the role pin

   // read the address pin, establish our role
-  if ( digitalRead(role_pin) )
+  if ( role_pin==1 )
     role = role_ping_out;
   else
     role = role_pong_back;


Update SparkCore.ino

Update SparkCore.ino

--- firmware/examples/Transports/SparkCore/SparkCore.ino
+++ firmware/examples/Transports/SparkCore/SparkCore.ino
@@ -15,7 +15,7 @@
  **************************************************************/
 //#define BLYNK_DEBUG // Uncomment this to see debug prints
 #define BLYNK_PRINT Serial
-#include "blynk/blynk.h"
+#include "blynk/BlynkSimpleSparkCore.h"

 // You should get Auth Token in the Blynk App.
 // Go to the Project Settings (nut icon).


No bite operations

No bite operations

--- LightScale/LightScale.ino
+++ LightScale/LightScale.ino
@@ -1,4 +1,5 @@
-const byte SCALE_VALUE[] = { 0b00000100, 0b00001100, 0b00011100, 0b00111100};
+const int SCALE_PINS[] = { 2, 3, 4, 5};
+const int SCALE_LEN = 4;

 // fotorezistor - A1, termistor - A0
 int senzor = A1;
@@ -6,8 +7,11 @@
 void setup() {
   Serial.begin(9600);
   pinMode(senzor, INPUT);
+
   // porty 2,3,4,5 jako vystup
-  DDRD |= 0b00111100;
+  for (int i = 0; i < SCALE_LEN; i++) {
+    pinMode(SCALE_PINS[i], OUTPUT);
+  }
 }

 void loop() {
@@ -15,11 +19,16 @@
   Serial.println(light);

   int scale = map(light, 300, 1000, 0, 3);
-  Serial.println(scale);
-
-  PORTD &= !0b00111100; // nastaveni vychoziho stavu - zhasnuto
-  PORTD |= (0b00000100 << scale);
-  // PORTD |= SCALE_VALUE[scale];
+
+  // vse zhasnout
+  for (int i = 0; i < SCALE_LEN; i++) {
+    digitalWrite(SCALE_PINS[i], LOW);
+  }
+
+  // zobrazit novou hodnotu
+  for (int i = 0; i < scale; i++) {
+    digitalWrite(SCALE_PINS[i], HIGH);
+  }

   delay(200);
 }


Allow the gateway to discover the intended roles for each of the multiple Arduinos attached to the Pi

--- MagnusCoreNeoPixel_v2.ino
+++ MagnusCoreNeoPixel_v2.ino
@@ -1,6 +1,5 @@
 #include <Adafruit_NeoPixel.h>
 #include <stdlib.h>
-

 // first communication pin for neo pixel string
 #define BASE_PIN 2
@@ -107,23 +106,30 @@
   if( collect_serial() )
   {
     // we have valid buffer of serial input
-    if( command[0] == 'e' || command[0] == 'E' )
-    {
+    switch (command[0]) {
+    case '*':
+        Serial.println("Magnus Core Node");
+    break;
+    case 'E':
+    case 'e':
       owner = enlightened;
       percent = getPercent(&command[1]);
-    }
-    else if( command[0] == 'r' || command[0] == 'R' )
-    {
+      break;
+    case 'R':
+    case 'r':
       owner = resistance;
       percent = getPercent(&command[1]);
-    }
-    else if( command[0] == 'n' || command[0] == 'N' )
-    {
+      break;
+    case 'n':
+    case 'N':
       owner = neutral;
       percent = 100;
-    }
+      break;
+    default:
+    Serial.println("?");
     //Serial.print((char *)command); Serial.print(" - ");Serial.print(command[0],DEC);Serial.print(": ");
     //Serial.print("owner "); Serial.print(owner,DEC); Serial.print(", percent "); Serial.println(percent,DEC);
+  }
   }

   if(strings[dir].timing < millis() )
@@ -163,4 +169,4 @@

 }

-
+


Full version, 80% of program space!

Full version, 80% of program space!

--- src/MQTT-monitor.ino
+++ src/MQTT-monitor.ino
@@ -26,55 +26,102 @@
  **************************************************************/

 // Select your modem:
-// #define TINY_GSM_MODEM_SIM800
-// #define TINY_GSM_MODEM_SIM900
-// #define TINY_GSM_MODEM_A6
-// #define TINY_GSM_MODEM_A7
 #define TINY_GSM_MODEM_M590
-// #define TINY_GSM_MODEM_ESP8266

 #include <TinyGsmClient.h>
 #include <PubSubClient.h>
-#include <OneWire.h>
+
 #include <SimpleDHT.h>
+#include <SPI.h>
+#include <Adafruit_Sensor.h>
+
+// Edit BME280_ADDRESS (0x76)
+#include <Adafruit_BME280.h>
+
+#include <Adafruit_SleepyDog.h>

 // Your GPRS credentials
 // Leave empty, if missing user or pass
-const char apn[]  = "";
+const char apn[]  = "internet";
 const char user[] = "";
 const char pass[] = "";
+const char mqtt_user[] = "valpuri";
+const char mqtt_pass[] = "ammu1001";

 // Use Hardware Serial on Mega, Leonardo, Micro
-#define SerialAT Serial1
+//#define SerialAT Serial1

 // or Software Serial on Uno, Nano
-//#include <SoftwareSerial.h>
-//SoftwareSerial SerialAT(2, 3); // RX, TX
-
+#include <SoftwareSerial.h>
+SoftwareSerial SerialAT(2, 3); // RX, TX
 TinyGsm modem(SerialAT);
 TinyGsmClient client(modem);
 PubSubClient mqtt(client);

-const char* broker = "test.mosquitto.org";
-
-const char* topicLed = "GsmClientTest/led";
-const char* topicInit = "GsmClientTest/init";
-const char* topicLedStatus = "GsmClientTest/ledStatus";
-
-#define LED_PIN 13
-int ledStatus = LOW;
+SimpleDHT22 dht22;
+
+Adafruit_BME280 bme;
+
+const char broker[] = "kw.dy.fi";
+
+const char topicHeater[] = "Karttula/Lammitin/";
+const char topicHeaterStatus[] = "Karttula/LammitinStatus/";
+const char topicInit[] = "Karttula/init/";
+const char topicOlohuone[] = "Karttula/Olohuone/";
+const char topicMakuuhuone[] = "Karttula/Makuuhuone/";
+const char topicVierashuone[] = "Karttula/Vierashuone/";
+const char topicWC[] = "Karttula/WC/";
+
+const char tempprefix[] = "T/";
+const char humprefix[] = "RH/";
+const char pressprefix[] = "P/";
+
+#define Makuuhuone 4
+#define WC 5
+#define Vierashuone 6
+
+#define HEATER_PIN 7
+#define GSM_RESET_PIN 8
+
+int HeaterStatus = LOW;

 long lastReconnectAttempt = 0;
+unsigned long lastrun = millis();
+int state = 0;
+//#define PERIOD 5*60*1000
+#define PERIOD 3000
+
+bool bme_status;
+
+#define TOPICBUFLEN 36
+#define VALBUFLEN 10
+
+char topicbuffer[TOPICBUFLEN];
+char valbuffer[VALBUFLEN];

 void setup() {
-  pinMode(LED_PIN, OUTPUT);
-
+
+  int countdownMS = Watchdog.enable(20000);
+
+  pinMode(HEATER_PIN, OUTPUT);
+  pinMode(GSM_RESET_PIN, OUTPUT);
+
+  // Turn heater off by default
+  digitalWrite(HEATER_PIN, LOW);
+
+  // Reset GSM module
+  digitalWrite(GSM_RESET_PIN, LOW);
+  delay(100);
+  digitalWrite(GSM_RESET_PIN, HIGH);
+  delay(500);
+  digitalWrite(GSM_RESET_PIN, LOW);
+
   // Set console baud rate
   Serial.begin(115200);
   delay(10);

   // Set GSM module baud rate
-  SerialAT.begin(115200);
+  SerialAT.begin(9600);
   delay(3000);

   // Restart takes quite some time
@@ -99,28 +146,56 @@
     while (true);
   }
   Serial.println(" OK");
-
+
   // MQTT Broker setup
   mqtt.setServer(broker, 1883);
   mqtt.setCallback(mqttCallback);
+
+  bme_status = bme.begin();
+  Watchdog.reset();
 }

 boolean mqttConnect() {
   Serial.print("Connecting to ");
   Serial.print(broker);
-  if (!mqtt.connect("GsmClientTest")) {
+  if (!mqtt.connect("Karttula", mqtt_user, mqtt_pass)) {
     Serial.println(" fail");
     return false;
   }
   Serial.println(" OK");
-  mqtt.publish(topicInit, "GsmClientTest started");
-  mqtt.subscribe(topicLed);
+  mqtt.publish(topicInit, "Karttula started");
+  mqtt.subscribe(topicHeater);
   return mqtt.connected();
 }

 void loop() {

   if (mqtt.connected()) {
+    //  if (1) {
+    if (millis() > (lastrun + PERIOD)) {
+      switch(state) {
+      case 0:
+	senddht22(Makuuhuone, topicMakuuhuone);
+	state++;
+	break;
+
+      case 1:
+	sendbme(topicOlohuone);
+	state++;
+	break;
+
+      case 2:
+	senddht22(WC, topicWC);
+	state++;
+	break;
+
+      case 3:
+	// Foo
+	state = 0;
+	lastrun = millis();
+      }
+    }
+    delay(1000);
     mqtt.loop();
   } else {
     // Reconnect every 10 seconds
@@ -132,7 +207,6 @@
       }
     }
   }
-
 }

 void mqttCallback(char* topic, byte* payload, unsigned int len) {
@@ -143,9 +217,57 @@
   Serial.println();

   // Only proceed if incoming message's topic matches
-  if (String(topic) == topicLed) {
-    ledStatus = !ledStatus;
-    digitalWrite(LED_PIN, ledStatus);
-    mqtt.publish(topicLedStatus, ledStatus ? "1" : "0");
-  }
-}
+  if (String(topic) == topicHeater) {
+    HeaterStatus = payload[0] == '0' ? LOW : HIGH;
+    digitalWrite(HEATER_PIN, HeaterStatus);
+    mqtt.publish(topicHeaterStatus, HeaterStatus ? "1" : "0");
+  }
+}
+
+void senddht22(int pinDHT22, char* topic) {
+  float temperature = 0;
+  float humidity = 0;
+  int err = SimpleDHTErrSuccess;
+  size_t len = strlen(topic);
+
+  if ((err = dht22.read2(pinDHT22, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
+    delay(2000);
+    Serial.println("DHT init failed");
+    return;
+  }
+
+  strcpy(topicbuffer,topic);
+
+  strcpy(topicbuffer + len, tempprefix);
+  dtostrf(temperature, 0, 1, valbuffer);
+  mqtt.publish(topicbuffer, valbuffer);
+
+  strcpy(topicbuffer + len, humprefix);
+  dtostrf(humidity, 0, 1, valbuffer);
+  mqtt.publish(topicbuffer, valbuffer);
+}
+
+void sendbme(char* topic) {
+  float temperature = 0;
+  float humidity = 0;
+  size_t len = strlen(topic);
+
+  if (bme_status) {
+    strcpy(topicbuffer,topic);
+
+    strcpy(topicbuffer + len, tempprefix);
+    dtostrf(bme.readTemperature(), 0, 1, valbuffer);
+    mqtt.publish(topicbuffer, valbuffer);
+
+    strcpy(topicbuffer + len, humprefix);
+    dtostrf(bme.readHumidity(), 0, 1, valbuffer);
+    mqtt.publish(topicbuffer, valbuffer);
+
+    strcpy(topicbuffer + len, pressprefix);
+    dtostrf(bme.readPressure(), 0, 2, valbuffer);
+    mqtt.publish(topicbuffer, valbuffer);
+  }
+}
+// foo
+
+  //  mqtt.publish(topic, xxx);


add energy saving

add energy saving

--- testing/arduino/self-driving-v3.ino
+++ testing/arduino/self-driving-v3.ino
@@ -6,6 +6,7 @@
 const uint8_t echoPin = 10;

 const uint8_t ledPin = 11;
+const bool ledBatterySaving = true;

 Adafruit_NeoPixel LEDStrip = Adafruit_NeoPixel(26, ledPin, NEO_GRB + NEO_KHZ800);

@@ -101,7 +102,10 @@
 void colorSet(uint32_t c) {
     for(uint16_t i=0; i < LEDStrip.numPixels(); i++)
     {
-        LEDStrip.setPixelColor(i, c);
+        if(ledBatterySaving && i%4 == 0 || !ledBatterySaving)
+        {
+            LEDStrip.setPixelColor(i, c);
+        }
     }
     LEDStrip.show();
 }


Name it better

Name it better

--- wireless/quickstart/wio-lte/Programmable_Wireless_Wio_LTE.ino
+++ wireless/quickstart/wio-lte/Programmable_Wireless_Wio_LTE.ino
@@ -1,6 +1,6 @@
 #include "ethernet.h"

-Ethernet eth = Ethernet();
+Ethernet lte = Ethernet();
 /* Setup variables for Twilio. The APN is fixed for Programmable Wireless. Feel free to change the URL and path. */
 const char      apn[20]         = "wireless.twilio.com";
 const char      URL[100]        = "s3.amazonaws.com";
@@ -23,31 +23,31 @@
 {
         /* Start Serial Output and GPRS */
         SerialUSB.begin(115200);
-        eth.Power_On();
+        lte.Power_On();
         SerialUSB.println("\n\rSerial working.");

-        while(!eth.Check_If_Power_On()) {
+        while(!lte.Check_If_Power_On()) {
                 SerialUSB.println("Waiting for module power up.");
                 delay(1000);
         }
-        while(!(eth.init())) {
+        while(!(lte.init())) {
                 SerialUSB.print("Initializing LTE...");
                 delay(1000);
         }
-        eth.join(apn);
+        lte.join(apn);

         /* Print out IP data if successful */
         SerialUSB.print("\n\rIP Address: ");
-        SerialUSB.print(eth.ip_string);
+        SerialUSB.print(lte.ip_string);

         /* Connect to host and path */
-        if(eth.connect(URL, port, TCP)) {
-                eth.write(path);
+        if(lte.connect(URL, port, TCP)) {
+                lte.write(path);
                 while(MODULE_PORT.available()) {
                         serialDebug.write(MODULE_PORT.read());
                 }
-                eth.close(1);
+                lte.close(1);
         } else {
                 SerialUSB.println("Connection Error!");
         }


fixed indentation and added fourirer series summer

--- julgran.ino
+++ julgran.ino
@@ -9,13 +9,19 @@
 #define GREEN 5
 #define BLUE 6

+// pi and 2*pi
+#define PI  3.141592654
+#define PI2 (PI*2)
+
 // network stuff
 #define PORT 8467
 #define BUFFSIZE 17
+
 byte mac[] = {0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02};
 byte ip[] = {192, 168, 1, 4};
 byte gateway[] = {192, 168, 1, 253};
 byte subnet[] = {255, 255, 255, 0};
+
 EthernetServer server = EthernetServer(PORT);

 /*
@@ -25,12 +31,12 @@
  * y(x):=A*sin(B/c*x+D)+E
  */
 struct colourFunction {
-  unsigned char a;
-  unsigned char b;
-  unsigned char c;
-  float bc; // bc = B / C
-  unsigned char d;
-  unsigned char e;
+	unsigned char a;
+	unsigned char b;
+	unsigned char c;
+	float bc; // bc = B / C
+	unsigned char d;
+	unsigned char e;
 };

 /*
@@ -39,10 +45,10 @@
  * the time between each iteration.
  */
 struct colourSettings {
-  unsigned char waittime;
-  struct colourFunction red;
-  struct colourFunction green;
-  struct colourFunction blue;
+	unsigned char waittime;
+	struct colourFunction red;
+	struct colourFunction green;
+	struct colourFunction blue;
 };

@@ -52,133 +58,169 @@

 void setup()
 {
-  Ethernet.begin(mac, ip, gateway, subnet);
-#if SER
-  Serial.begin(9600);
-  Serial.println(Ethernet.localIP());
-#endif
-  selfTest();
-  selfTest();
-  server.begin();
-
-  /* set a default program */
-  cs.waittime = 10;
-  cs.red.a = cs.green.a = cs.blue.a = 0;
-  cs.red.b = cs.green.b = cs.blue.b = 22;
-  cs.red.c = cs.green.c = cs.blue.c = 255;
-  cs.red.d = cs.green.d = cs.blue.d = 0;
-  cs.red.e = cs.green.e = cs.blue.e = 255;
-  int i = 0;
-
-  /* set buffer to 0 */
-  for (i; i<BUFFSIZE; i++) buff[i] = 0;
-}
-
+	Ethernet.begin(mac, ip, gateway, subnet);
+#if SER
+	Serial.begin(9600);
+	Serial.println(Ethernet.localIP());
+#endif
+	selfTest();
+	selfTest();
+	server.begin();
+
+	/* set a default program */
+	cs.waittime = 10;
+	cs.red.a = cs.green.a = cs.blue.a = 0;
+	cs.red.b = cs.green.b = cs.blue.b = 22;
+	cs.red.c = cs.green.c = cs.blue.c = 255;
+	cs.red.d = cs.green.d = cs.blue.d = 0;
+	cs.red.e = cs.green.e = cs.blue.e = 255;
+
+	/* set buffer to 0 */
+	memset(buff, 0, BUFFSIZE);
+}
+
+
+unsigned char fun(unsigned char a, unsigned char bc, unsigned char d,
+		unsigned char e)
+{
+	return a*sin(bc+d)+e;
+}

 void loop()
 {
-  EthernetClient client = server.available();
-  if (client == true) { /* got connection, read and parse data */
-    parsePacketIntoSettings(client);
-#if SER
-    printSettings();
-#endif
-  } else { /* there is no data available, update instead */
-    unsigned char r = cs.red.a * sin(x*cs.red.bc + cs.red.d) + cs.red.e;
-    unsigned char g = floor(cs.green.a * sin(x*cs.green.bc + cs.green.d)) + cs.green.e;
-    unsigned char b = cs.blue.a * sin(x*cs.blue.bc + cs.blue.d) + cs.blue.e;
-    analogWrite(RED, r);
-    analogWrite(GREEN, g);
-    analogWrite(BLUE, b);
-#if SER
-  //  Serial.println(cs.green.a*sin(x*cs.green.bc+cs.green.d)+cs.green.e);
-#endif
-    x++;
-    delay(cs.waittime);
-  }
-}
-
-void parsePacketIntoSettings(EthernetClient c)
-{
-  float a,b;
-  char v;
-
-  /* read data */
-  v = c.read(); /* read and discard this */
-  cs.waittime = c.read();
-  cs.red.a = c.read();
-  cs.red.b = c.read();
-  cs.red.c = c.read();
-  cs.red.d = c.read();
-  cs.red.e = c.read();
-  cs.green.a = c.read();
-  cs.green.b = c.read();
-  cs.green.c = c.read();
-  cs.green.d = c.read();
-  cs.green.e = c.read();
-  cs.blue.a = c.read();
-  cs.blue.b = c.read();
-  cs.blue.c = c.read();
-  cs.blue.d = c.read();
-  cs.blue.e = c.read();
-
-  /* create bc =:= b/c */
-  a = (float) cs.red.b;
-  b = (float) cs.red.c;
-  cs.red.bc = a/b;
-  a = (float) cs.green.b;
-  b = (float) cs.green.c;
-  cs.green.bc = a/b;
-  a = (float) cs.blue.b;
-  b = (float) cs.blue.c;
-  cs.blue.bc = a/b;
-#if SER
-  Serial.println(cs.red.bc);
-  Serial.println(cs.green.bc);
-  Serial.println(cs.blue.bc);
+	EthernetClient client = server.available();
+	if (client == true) { /* got connection, read and parse data */
+		parsePacketIntoSettings(client);
+#if SER
+		printSettings();
+#endif
+	} else { /* there is no data available, update instead */
+		unsigned char r = fun(cs.red.a, cs.red.bc, cs.red.d, cs.red.e);
+		unsigned char g = fun(cs.green.a, cs.green.bc, cs.green.d, cs.green.e);
+		unsigned char b = fun(cs.blue.a, cs.blue.bc, cs.blue.d, cs.blue.e);
+		analogWrite(RED, r);
+		analogWrite(GREEN, g);
+		analogWrite(BLUE, b);
+#if SER
+		//  Serial.println(cs.green.a*sin(x*cs.green.bc+cs.green.d)+cs.green.e);
+#endif
+		x++;
+		delay(cs.waittime);
+	}
+}
+
+void parsePacketIntoSettings(EthernetClient client)
+{
+	float b,c;
+
+	/* read and discard the first byte */
+	(void) client.read();
+
+	/* read data */
+	cs.waittime = client.read();
+	cs.red.a = client.read();
+	cs.red.b = client.read();
+	cs.red.c = client.read();
+	cs.red.d = client.read();
+	cs.red.e = client.read();
+	cs.green.a = client.read();
+	cs.green.b = client.read();
+	cs.green.c = client.read();
+	cs.green.d = client.read();
+	cs.green.e = client.read();
+	cs.blue.a = client.read();
+	cs.blue.b = client.read();
+	cs.blue.c = client.read();
+	cs.blue.d = client.read();
+	cs.blue.e = client.read();
+
+	/* create bc = b/c */
+	b = (float) cs.red.b;
+	c = (float) cs.red.c;
+	cs.red.bc = b/c;
+	b = (float) cs.green.b;
+	c = (float) cs.green.c;
+	cs.green.bc = b/c;
+	b = (float) cs.blue.b;
+	c = (float) cs.blue.c;
+	cs.blue.bc = b/c;
+#if SER
+	Serial.println(cs.red.bc);
+	Serial.println(cs.green.bc);
+	Serial.println(cs.blue.bc);
 #endif
 }
 #if SER
 void printSettings()
 {
-  Serial.println("****************************************");
-  Serial.print("Waittime: ");
-  Serial.print(cs.waittime, DEC);
-  Serial.println(" ms");
-  Serial.print("Red:      r(t)=");
-  Serial.print(cs.red.a, DEC); Serial.print("*sin(");
-  Serial.print(cs.red.b, DEC); Serial.print("*t/");
-  Serial.print(cs.red.c, DEC); Serial.print("+");
-  Serial.print(cs.red.d, DEC); Serial.print(")+");
-  Serial.print(cs.red.e, DEC); Serial.print("\n");
-  Serial.print("Green:    g(t)=");
-  Serial.print(cs.green.a, DEC); Serial.print("*sin(");
-  Serial.print(cs.green.b, DEC); Serial.print("/");
-  Serial.print(cs.green.c, DEC); Serial.print("*t+");
-  Serial.print(cs.green.d, DEC); Serial.print(")+");
-  Serial.print(cs.green.e, DEC); Serial.print("\n");
-  Serial.print("Blue:     b(t)=");
-  Serial.print(cs.blue.a, DEC); Serial.print("*sin(");
-  Serial.print(cs.blue.b, DEC); Serial.print("/");
-  Serial.print(cs.blue.c, DEC); Serial.print("*t+");
-  Serial.print(cs.blue.e, DEC); Serial.print(")+");
-  Serial.print(cs.blue.e, DEC); Serial.print("\n");
-  Serial.println("****************************************");
+	Serial.println("****************************************");
+	Serial.print("Waittime: ");
+	Serial.print(cs.waittime, DEC);
+	Serial.println(" ms");
+	Serial.print("Red:   r(t)=");
+	Serial.print(cs.red.a, DEC); Serial.print("*sin(");
+	Serial.print(cs.red.b, DEC); Serial.print("*t/");
+	Serial.print(cs.red.c, DEC); Serial.print("+");
+	Serial.print(cs.red.d, DEC); Serial.print(")+");
+	Serial.print(cs.red.e, DEC); Serial.print("\n");
+	Serial.print("Green: g(t)=");
+	Serial.print(cs.green.a, DEC); Serial.print("*sin(");
+	Serial.print(cs.green.b, DEC); Serial.print("/");
+	Serial.print(cs.green.c, DEC); Serial.print("*t+");
+	Serial.print(cs.green.d, DEC); Serial.print(")+");
+	Serial.print(cs.green.e, DEC); Serial.print("\n");
+	Serial.print("Blue:  b(t)=");
+	Serial.print(cs.blue.a, DEC); Serial.print("*sin(");
+	Serial.print(cs.blue.b, DEC); Serial.print("/");
+	Serial.print(cs.blue.c, DEC); Serial.print("*t+");
+	Serial.print(cs.blue.e, DEC); Serial.print(")+");
+	Serial.print(cs.blue.e, DEC); Serial.print("\n");
+	Serial.println("****************************************");
 }
 #endif
 void selfTest()
 {
-  analogWrite(RED, 0);
-  analogWrite(GREEN, 0);
-  analogWrite(BLUE, 0);
-
-  analogWrite(RED, 255);
-  delay(1000);
-  analogWrite(RED, 0);
-  analogWrite(GREEN, 255);
-  delay(1000);
-  analogWrite(GREEN, 0);
-  analogWrite(BLUE, 255);
-  delay(1000);
-  analogWrite(BLUE, 0);
-}
+	/* make sure the leds are off */
+	analogWrite(RED,   0);
+	analogWrite(GREEN, 0);
+	analogWrite(BLUE,   0);
+
+	/* turn on each led for a second */
+	analogWrite(RED,   255); delay(1000); analogWrite(RED,   0);
+	analogWrite(GREEN, 255); delay(1000); analogWrite(GREEN, 0);
+	analogWrite(BLUE,  255); delay(1000); analogWrite(BLUE,  0);
+
+	/* make sure the leds are off */
+	analogWrite(RED,   0);
+	analogWrite(GREEN, 0);
+	analogWrite(BLUE,  0);
+}
+
+/*
+ * Compute the fourier series in the point x.
+ * an[] An array of size N with the an coefficients
+ * bn[] An array of size N with the bn coefficients
+ * See http://en.wikipedia.org/wiki/Fourier_series.
+ */
+int fourier(int x, float an[], float bn[], float a0, int N, float P)
+{
+	float val = a0;
+	float pre = PI2*x/P;
+
+#ifdef SER
+	unsigned long time = micros();
+#endif
+
+	for (int i=1; i<N; i++) {
+		val += an[i-1]*cos(pre*i) + bn[i-1]*sin(pre*i);
+	}
+
+#ifdef SER
+	unsigned long diff = micros() - time;
+	Serial.print("Fourier took ");
+	Serial.print(diff, DEC);
+	Serial.println(" micro seconds");
+#endif
+
+	return (int) val;
+}


debug info

debug info

--- src/neurite.ino
+++ src/neurite.ino
@@ -1178,6 +1178,7 @@
 		token = strtok(NULL, "\0");
 		if (token) {
 			int val = atoi(token);
+			log_dbg("hit light, msg(value): %s(%d)\n\r", token, val);
 			analogWrite(14, val);
 		}
 	} else if (strcmp(token, "servo:") == 0) {