Полное переписание с нуля

Полное переписание с нуля

--- main.ino
+++ main.ino
@@ -1,697 +1,179 @@
-#include <EEPROM.h>
-#include <Time.h>
-#include <Wire.h>
-#include <DS1307RTC.h>
-#include <LiquidCrystal_I2C.h>
-
-LiquidCrystal_I2C lcd(0x27,16,2); // Инициализация дисплея (адрес, количество символов, количество строк)
-
-#define VERSION "0.8(a)"
-#define DEBUG
-
-static byte	bat_icon[8] = {
-	B01110,
-	B11111,
-	B11111,
-	B11111,
-	B11111,
-	B11111,
-	B11111,
-	B11111
-};
-
-struct sys_conf {
-	int		password[6];		// Пароль, для отключения сигнала
-
-	int		BUTTON_OK,
-			BUTTON_UP,
-			BUTTON_DOWN,
-			BUTTON_SIGNAL;
-
-	byte	red_speed,			// Включать ли красный свет при уменьшении скорости
-			time_to_slpeep,		// Время, после которого компьютер уснёт (минуты)
-			auto_led,			// Включать подсветку экрана по датчику света или нет
-			auto_headlights;	// Включать фару по датчику света или нет
-
-	float	distance,
-			max_speed;
-};
-
-/*Стандартные значения*/
-#define WHEEL_LENGTH	0.193	// Длина окружности колеса в метрах
-#define BIP_DELAY		4		// Сколько итераций пищать (* 500 / 10000)
-
-/*Аналоговые выводы*/
-#define ACTION_BUTTON	6
-#define LIGHT_SENSOR	7
-
-/*Цифровые выводы*/
-#define	PWM_S1			5
-#define	PWM_S2			6
-#define	PWM_S3			9
-#define BIP				4
-#define DISPLAY_LIGHT	10
-#define VIBRO_SENSOR	7
-
-/*Системные макросы*/
-#define SWITCH_NEXT		150		// Врямя в мс до переключения на следующий пункт при зажатой кнопке
-#define LONG_PRESS		2000	// Время долгого нажатия кнопки
-
-bool			alarm_state		= false;	// Для сигнализации
-
-unsigned long	lastturn;	// Время последнего обращения
-
-float			speed_now		= 0.0,	// Скорость
-				distance		= 0.0;	// Расстояние
-
-byte			bat_percent		= 100,
-				system_state	= 0;
-
-#define SPEED_STATE		0
-#define MENU_STATE		1
-#define SETTINGS_STATE	2
-
-sys_conf		btc_config; // Конфигурация системы
-
-void setup() {
-	#ifdef DEBUG
-	Serial.begin(9600);
-	#endif
-
-	/*Инициализация дисплея*/
-	lcd.begin();
-	pinMode(DISPLAY_LIGHT, OUTPUT);
-	pinMode(VIBRO_SENSOR, OUTPUT);
-	analogWrite(DISPLAY_LIGHT, 175);	// Включение подсветки
-
-	lcd.print("Loading system..");
-	lcd.setCursor(0, 1);
-	lcd.print("Version: ");
-	lcd.print(VERSION);
-
-	pinMode(PWM_S1, OUTPUT);
-	pinMode(PWM_S2, OUTPUT);
-	pinMode(PWM_S3, OUTPUT);
-
-	tone(BIP, 100, 250);
-	delay(250);
-	tone(BIP, 100, 250);
-	delay(1000);
-
-	setSyncProvider(RTC.get);			// Для времени
-
-	/*Инициализация выводов для сигнала*/
-	pinMode(BIP, OUTPUT);
-
-	/*Прерывание на 2-ом цифровом канале для сигнализации*/
-	attachInterrupt(0, alarm, CHANGE);
-
-	/*Прерывание на 3-ем цифровом канале для подсчёта скорости*/
-	// attachInterrupt(1, speed, CHANGE);
-
-	lcd.createChar(0, bat_icon);
-
-	#ifdef FIRST_ON
-	sys_conf load_to_eeprom;
-
-	load_to_eeprom.password[0]		= 1;
-	load_to_eeprom.password[1]		= 2;
-	load_to_eeprom.password[2]		= 3;
-	load_to_eeprom.password[3]		= 4;
-	load_to_eeprom.red_speed		= true;
-	load_to_eeprom.time_to_slpeep = 5;
-	load_to_eeprom.auto_led		 = true;
-	load_to_eeprom.auto_headlights	= true;
-	load_to_eeprom.distance		 = 0.0;
-	load_to_eeprom.max_speed		= 0.0;
-
-	WriteSysConfEEPROM(load_to_eeprom, 0);
-	lcd.print("All OK!");
-	#endif
-	colibration();
-}
-
-/*Interrupt zone start*/
-void alarm() {	// Сигнализация
-	if ((!alarm_state) && (system_state == 1)) {
-		alarm_state = true;
-
-		for (int	i = 0; i < BIP_DELAY; i++) {
-			tone(BIP, 750);
-			delay(500);
-			tone(BIP, 300);
-			delay(500);
-		}
-		noTone(BIP);
-		alarm_state = false;
-	}
-}
-
-void speed() {	// Подсчёт скорости
-	if ((millis() - lastturn) > 80) { // Защита от случайных измерений (основано на том, что велосипед не будет ехать быстрее 120 кмч)
-		speed_now = WHEEL_LENGTH / ((float)(millis() - lastturn) / 1000) * 3.6; // Расчет скорости, км/ч
-		lastturn	= millis();													 // Запомнить время последнего оборота
-		distance	= distance + WHEEL_LENGTH / 1000;							 // Прибавляем длину колеса к дистанции при каждом обороте
-	}
-}
-/*Interrupt zone end*/
-
-void loop() {
-	first_on();
-	if (system_state == SPEED_STATE) {
-		road_mode();
-	}
-
-	if (system_state == MENU_STATE) {
-		#ifdef DEBUG
-		char menu_array[6][15]	= {
-		#else
-		char menu_array[5][15]	= {
-		#endif
-			"Blue spark",
-			"COOL MODE",
-			"Speedometr",
-			"Statistik",
-		#ifdef DEBUG
-			"Settings",
-			"Self test"
-		#else
-			"Settings"
-		#endif
-		};
-
-		#ifdef DEBUG
-		switch (display_list(6, menu_array)) {
-		#else
-		switch (display_list(5, menu_array)) {
-		#endif
-			case 0:	if (digitalRead(PWM_S2) == LOW) {
-						digitalWrite(PWM_S2, HIGH);
-					} else {
-						digitalWrite(PWM_S2, LOW);
-					}
-					break;
-
-			case 1: cool_mode();
-					break;
-
-			case 2: system_state	= SPEED_STATE;
-					break;
-
-			case 4: system_state	= SETTINGS_STATE;
-					break;
-
-			#ifdef DEBUG
-			case 5: self_test();
-					break;
-			#endif
-		}
-	}
-
-	if (system_state == SETTINGS_STATE) {
-		char settings_array[6][15]	= {
-			"Password",
-			"Display",
-			"Light settings",
-			"Time setting",
-			"About system",
-			"Back"
-		};
-
-		switch (display_list(6, settings_array)) {
-			case 0: if (read_password())
-						input_password();
-					break;
-
-			case 3:	TimeElements	t_n;
-					time_t			timeVal;
-					t_n.Second	= 0;
-					t_n.Hour	= input_int_number("Input hour", 0, 23);
-					t_n.Minute	= input_int_number("Input minutes", 0, 59);
-					t_n.Day		= input_int_number("Input day", 1, 31);
-					t_n.Month	= input_int_number("Input month", 1, 12);
-					t_n.Year	= input_int_number("Input year", 15, 20) + 30;
-					timeVal		= makeTime(t_n);
-					RTC.set(timeVal);
-					setTime(timeVal);
-					break;
-
-			case 5: system_state	= MENU_STATE;
-					break;
-		}
-	}
-}
-
-void cool_mode () {
-	lcd.clear();
-	lcd.print("   COOL MODE");
-	byte light_level;
-
-	digitalWrite(PWM_S1, LOW);
-
-	while (analogRead(ACTION_BUTTON) < 5) {
-		for (light_level	= 0; light_level < 255; light_level++, delay(10), analogWrite(PWM_S2, light_level));
-		for (light_level	= 255; light_level != 0; light_level--, delay(10), analogWrite(PWM_S2, light_level));
-	}
-
-	while (analogRead(ACTION_BUTTON) > 5);
-}
-
-void alarm_mode() {
-	lcd.clear();
-	lcd.print(" Stand By Mode");
-	digitalWrite(DISPLAY_LIGHT, LOW);
-	digitalWrite(VIBRO_SENSOR, HIGH);
-	alarm_state		= false;
-	system_state	= 1;
-	while (true) {
-		while (analogRead(ACTION_BUTTON) < 5);
-		if (read_password())
-			break;
-	}
-	digitalWrite(VIBRO_SENSOR, LOW);
-}
-
-byte input_int_number(const char *text, byte min_num, byte max_num) {	// Ввод целочисленного числа
-	lcd.clear();
-	lcd.print(text);
-
-	int		key_now;
-
-	byte	same_num = min_num;
-
-	while (true) {
-		lcd.setCursor(0, 1);
-		lcd.print("   ");
-
-		lcd.setCursor(0, 1);
-		lcd.print(same_num);
-		key_now	= key_pressed();
-
-		if (key_now == btc_config.BUTTON_UP) {
-			if (same_num == max_num) {
-				same_num	= min_num;
-			} else {
-				same_num++;
-			}
-		} else if (key_now == btc_config.BUTTON_DOWN) {
-			if (same_num == min_num) {
-				same_num	= max_num;
-			} else {
-				same_num--;
-			}
-		} else if (key_now == btc_config.BUTTON_OK) {
-			return same_num;
-		}
-	}
-}
-
-float input_float_number(char text[], float min_num, float max_num) {	// Ввод числа с точкой
-	lcd.clear();
-	lcd.print(text);
-
-	float	same_num = min_num;
-
-	int		key_now;
-
-	while (true) {
-		lcd.setCursor(0, 1);
-		lcd.print("                ");
-		lcd.setCursor(0, 1);
-		lcd.print(same_num);
-
-		key_now	= key_pressed();
-
-		if (key_now == btc_config.BUTTON_UP) {
-			if ((same_num + 0.1) > max_num) {
-				same_num	= min_num;
-			} else {
-				same_num	+= 0.1;
-			}
-		} else if (key_now == btc_config.BUTTON_DOWN) {
-			if ((same_num - 0.1) < min_num) {
-				same_num	= max_num;
-			} else {
-				same_num	-= 0.1;
-			}
-		} else if (key_now == btc_config.BUTTON_OK) {
-			return same_num;
-		}
-	}
-}
-
-void sys_watch() {
-	if (analogRead(LIGHT_SENSOR) > 600) {
-		digitalWrite(DISPLAY_LIGHT, LOW);
-		digitalWrite(PWM_S1, LOW);
-	} else {
-		digitalWrite(DISPLAY_LIGHT, HIGH);
-		digitalWrite(PWM_S1, HIGH);
-	}
-}
-
-void stand_by_mode() {
-
-}
-
-unsigned int key_pressed() {	// Определение нажатой кнопки
-	int	key,
-		delay_time	= 0;
-
-	while (true) {
-		sys_watch();
-
-		key	= analogRead(ACTION_BUTTON);
-
-		#ifdef DEBUG
-		Serial.println(key);
-		#endif
-
-		if ((key >= btc_config.BUTTON_OK - 5) && (key <= btc_config.BUTTON_OK + 5)) {
-			key = btc_config.BUTTON_OK;
-			break;
-		} else if ((key >= btc_config.BUTTON_UP - 5) && (key <= btc_config.BUTTON_UP + 5)) {
-			key = btc_config.BUTTON_UP;
-			break;
-		} else if ((key >= btc_config.BUTTON_DOWN - 5) && (key <= btc_config.BUTTON_DOWN + 5)) {
-			key = btc_config.BUTTON_DOWN;
-			break;
-		}
-	}
-
-	while ((analogRead(ACTION_BUTTON) > 5) && (delay_time < SWITCH_NEXT)) {	// Ожидание зажатия
-		delay(1);
-		delay_time++;
-	}
-
-	return key;
-}
-
-void road_mode() {	// Режим спидометра
-	float	speed_old = 0.1;
-
-	int		key_now;
-
-	lcd.clear();
-	lcd.print("km/h: ");
-
-	lcd.setCursor(0, 1);
-	lcd.print("km:");
-
-	lcd.setCursor(15, 1);
-	lcd.write(0);
-
-	while (system_state == SPEED_STATE) {
-		if (speed_old > speed_now) {
-			lcd.setCursor(5, 0);
-			lcd.print("		");
-		}
-
-		if (speed_old != speed_now) {
-			lcd.setCursor(5, 0);
-			lcd.print(speed_now);
-			speed_old	= speed_now;
-		}
-
-		/*TIME START*/
-		lcd.setCursor(11, 0);
-
-		if (hour() < 10) {
-			lcd.print("0");
-		}
-
-		lcd.print(hour());
-		lcd.print(":");
-
-		lcd.setCursor(14, 0);
-
-		if (minute() < 10) {
-			lcd.print("0");
-		}
-
-		lcd.print(minute());
-		/*TIME END*/
-
-		lcd.setCursor(3, 1);
-		lcd.print(distance);
-
-		lcd.setCursor(12, 1);
-		if (bat_percent == 100) {
-			lcd.print("100");
-		} else if ((bat_percent > 100) && (bat_percent <= 10)){
-			lcd.print(" ");
-			lcd.print(bat_percent);
-		} else if (bat_percent > 10){
-			lcd.print("	");
-			lcd.print(bat_percent);
-		}
-
-		key_now	= analogRead(ACTION_BUTTON);
-
-		#ifdef DEBUG
-		Serial.print("Key in road_mode: ");
-		Serial.println(key_now);
-		#endif
-
-		if ((key_now >= btc_config.BUTTON_OK - 5) && (key_now <= btc_config.BUTTON_OK + 5)) {
-			while (analogRead(ACTION_BUTTON) > 5);
-			delay(50);
-			lcd.clear();
-			system_state	= MENU_STATE;
-			break;
-		}
-
-		sys_watch();
-	}
-}
-
-void first_on() {
-	lcd.clear();
-	lcd.print("Hello!");
-
-	for (byte	i = 0; i < 255; i++, delay(4)) {
-		analogWrite(DISPLAY_LIGHT, i);
-	}
-}
-
-byte display_list(byte all_element, char settings_array[][15]) {
-	lcd.clear();
-
-	byte	selected		= 0,
-			on_display		= 0;
-
-	int	 key_now;
-
-	bool	key_pressed_ok	= true;
-
-	while (true) {
-		if (key_pressed_ok) {
-			if (selected == on_display) {
-				lcd.setCursor(0,0);
-				lcd.print(">");
-				lcd.setCursor(0,1);
-				lcd.print(" ");
-			} else {
-				lcd.setCursor(0,1);
-				lcd.print(">");
-				lcd.setCursor(0,0);
-				lcd.print(" ");
-			}
-
-			lcd.setCursor(1,0);
-			lcd.print(settings_array[on_display]);
-
-			if (on_display + 1 < all_element) {
-				lcd.setCursor(1,1);
-				lcd.print(settings_array[on_display + 1]);
-			}
-		}
-
-		key_pressed_ok	= true;
-
-		key_now = key_pressed();
-		Serial.print("key_now: ");
-		Serial.println(key_now);
-
-		if (key_now == btc_config.BUTTON_OK) {
-			return selected;
-		} else if (key_now == btc_config.BUTTON_UP) {
-			if (selected != 0) {
-				if (selected == on_display) {
-					lcd.clear();
-					on_display	-= 2;
-				}
-
-				selected--;
-			}
-		} else if (key_now == btc_config.BUTTON_DOWN) {
-			if (selected < all_element - 1) {
-				if (selected == (on_display + 1)) {
-					lcd.clear();
-					on_display	+= 2;
-				}
-
-				selected++;
-			}
-		} else {
-			key_pressed_ok	= false;
-		}
-	}
-}
-
-void WriteSysConfEEPROM(sys_conf str, int base) { // Запись и чтение выполнены великолепным программистом Виктором Охотниковым
-	char	*c;
-	int	 structSize = sizeof(sys_conf);
-
-	c = (char *) &str;
-
-	for(int i = 0; i < structSize; i++) {
-		EEPROM.write(i+base, *c);
-		c++;
-	}
-}
-
-void ReadSysConfEEPROM(sys_conf *str, int base) {
-	char	*c;
-	int	 structSize = sizeof(sys_conf);
-
-	c = (char *) str;
-
-	for(int i = 0; i < structSize; i++) {
-		*c = EEPROM.read(i+base);
-		c++;
-	}
-}
-
-void input_password() {
-	lcd.clear();			// Очистка экрана
-	lcd.print("New password");
-
-	lcd.setCursor(0, 1);	// Установка указателя в левый верхний угол
-	lcd.print("Password: ");
-
-	for (byte i = 0; i < 6; i++) {
-		btc_config.password[i]	= key_pressed();
-		lcd.print("*");
-	}
-
-	lcd.clear();
-	lcd.print("Complete!");
-	delay(2000);
-}
-
-bool read_password() {
-	bool	wrong = false;
-
-	lcd.clear();			// Очистка экрана
-	lcd.print("Current password");
-
-	lcd.setCursor(0, 1);	// Установка указателя в левый верхний угол
-	lcd.print("Password: ");
-
-	for (byte i = 0; i < 6; i++) {
-		if (btc_config.password[i]	!= key_pressed()) {
-			wrong = true;
-		}
-
-		lcd.print("*");
-	}
-
-	lcd.clear();
-	if (wrong) {
-		lcd.print("Incorrect!");
-		delay(2000);
-		return	false;
-	} else {
-		lcd.print("Pass!");
-		delay(2000);
-		return	true;
-	}
-
-	return false;
-}
-
-void colibration() {
-	byte	key_num = 0;
-
-	while (key_num != 3) {
-		while (analogRead(ACTION_BUTTON) > 5);
-		lcd.clear();
-
-		if (key_num == 0) {
-			lcd.print("Press OK key");
-			lcd.setCursor(0, 1);
-
-			while ((btc_config.BUTTON_OK = analogRead(ACTION_BUTTON)) < 5);
-
-			lcd.print(btc_config.BUTTON_OK);
-			key_num++;
-			continue;
-		}
-
-		if (key_num == 1) {
-			lcd.print("Press UP key");
-			lcd.setCursor(0, 1);
-
-			while ((btc_config.BUTTON_UP = analogRead(ACTION_BUTTON)) < 5);
-
-			lcd.print(btc_config.BUTTON_UP);
-			key_num++;
-			continue;
-		}
-
-		if (key_num == 2) {
-			lcd.print("Press DOWN key");
-			lcd.setCursor(0, 1);
-
-			while ((btc_config.BUTTON_DOWN = analogRead(ACTION_BUTTON)) < 5);
-
-			lcd.print(btc_config.BUTTON_DOWN);
-			key_num++;
-			continue;
-		}
-
-		/*if (key_num == 0) {
-			lcd.print("Press OK key");
-			lcd.setCursor(1, 0);
-
-			while ((btc_config.BUTTON_OK = analogRead(ACTION_BUTTON)) < 5);
-
-			lcd.print(btc_config.BUTTON_OK);
-			key_num++;
-		}*/
-
-	}
-
-	while (analogRead(ACTION_BUTTON) > 5);
-}
-
-#ifdef DEBUG
-void self_test() {
-	lcd.clear();
-	lcd.print("Light sensor");
-
-	while (analogRead(ACTION_BUTTON) < 5) {
-		lcd.setCursor(0, 1);
-		lcd.print("    ");
-		lcd.setCursor(0, 1);
-		lcd.print(analogRead(LIGHT_SENSOR));
-		delay(500);
-	}
-
-	lcd.clear();
-	lcd.print("Key test");
-
-	while (analogRead(ACTION_BUTTON) > 5);
-
-	while (analogRead(ACTION_BUTTON) != btc_config.BUTTON_OK) {
-		lcd.setCursor(0, 1);
-		lcd.print("    ");
-		lcd.setCursor(0, 1);
-		lcd.print(analogRead(ACTION_BUTTON));
-		delay(500);
-	}
-
-	while (analogRead(ACTION_BUTTON) > 5);
-}
-#endif+/*
+	BLUE SPARK PROJECT
+*/
+
+#include <EEPROM.h>
+#include <Time.h>
+#include <Wire.h>
+#include <DS1307RTC.h>
+#include <LiquidCrystal_I2C.h>
+
+LiquidCrystal_I2C lcd(0x27,16,2); // Инициализация дисплея (адрес, количество символов, количество строк)
+
+#define VERSION "1.0(b)"
+#define DEBUG
+
+static byte	bat_icon[8] = {
+	B01110,
+	B11111,
+	B11111,
+	B11111,
+	B11111,
+	B11111,
+	B11111,
+	B11111
+};
+
+struct sys_conf {
+	int		password[6];		// Пароль, для отключения сигнала
+
+	int		button_ok,
+			button_up,
+			button_down,
+			button_signal,
+			lux_light_on,		// При какой яркости включать фару
+			lux_backlight_on,	// При какой яркости включать подсветку экрана
+			lux_headlight;		// Яркость фары
+
+	bool	red_speed,			// Включать ли красный свет при уменьшении скорости
+			auto_backlight,		// Включать подсветку экрана по датчику света или нет
+			auto_headlights,	// Включать фару по датчику света или нет
+			alarm_state;		// Для того, чтобы даже после сброса сигнализация не выключилась
+
+	byte	time_to_slpeep,		// Время, после которого компьютер уснёт (минуты)
+
+	float	distance,
+			max_speed,
+			wheel_length;		// Длина колеса
+};
+
+/*Стандартные значения*/
+#define BIP_DELAY			4	// Сколько итераций пищать (* 500 / 10000)
+
+/*Аналоговые выводы*/
+#define ACTION_BUTTON		6
+#define LIGHT_SENSOR		7
+
+/*Цифровые выводы*/
+#define BIP					4
+#define HEADLIGHT			5
+#define LOWER_LIGHT			6
+#define VIBRO_SENSOR		7
+#define LATCH_PIN			8
+#define RED_BACK_LIGHT		9
+#define DISPLAY_LIGHT		10
+#define DATA_PIN			11
+#define CLOCK_PIN			12
+#define EXT_ALARM			13
+
+/*Выводы на сдвиговом регистре*/
+#define LEFT_TURN_LIGHT		0
+#define RIGHT_TURN_LIGHT	1
+
+/*Системные макросы*/
+#define SWITCH_NEXT			150		// Врямя в мс до переключения на следующий пункт при зажатой кнопке
+#define LONG_PRESS			2000	// Время долгого нажатия кнопки
+
+unsigned long	lastturn;	// Время последнего обращения
+
+float		speed_now		= 0.0,	// Скорость
+			distance		= 0.0;	// Расстояние
+
+byte		bat_percent		= 100,
+			system_state	= 0;
+
+#define SPEED_STATE			0
+#define AlARM_STATE			1
+#define MENU_STATE			2
+#define SLEEP_STATE			3
+
+sys_conf		btc_config; // Конфигурация системы
+
+void setup() {
+	pinMode(DISPLAY_LIGHT, OUTPUT);		// Подключение подсветки экрана
+
+	for (byte	i	= 0; i < 255; i++, delay(8), analogWrite(DISPLAY_LIGHT, i));
+
+	lcd.begin();
+	lcd.print("Loading system...");
+	lcd.setCursor(0, 1);
+	lcd.print("Version: ");
+	lcd.print(VERSION);
+
+	/*Инициализация цифровых выводов*/
+	pinMode(BIP, OUTPUT);
+	pinMode(HEADLIGHT, OUTPUT);
+	pinMode(LOWER_LIGHT, OUTPUT);
+	pinMode(VIBRO_SENSOR, OUTPUT);
+	pinMode(LATCH_PIN, OUTPUT);
+	pinMode(RED_BACK_LIGHT, OUTPUT);
+	pinMode(DISPLAY_LIGHT, OUTPUT);
+	pinMode(DATA_PIN, OUTPUT);
+	pinMode(CLOCK_PIN, OUTPUT);
+	pinMode(EXT_ALARM, OUTPUT);
+
+	setSyncProvider(RTC.get);			// Для времени
+
+	/*Прерывания*/
+	attachInterrupt(0, alarm, CHANGE);
+	attachInterrupt(1, speed, CHANGE);
+
+	lcd.createChar(0, bat_icon);	// Загрузка иконки батареи
+}
+
+void loop() {
+
+}
+
+void alarm() {
+
+}
+
+void speed() {
+
+}
+
+void sys_watch() {
+	if ((btc_config.auto_headlights) && (analogRead(LIGHT_SENSOR) > btc_config.lux_light_on)) {	// Следилка за фарой
+		digitalWrite(HEADLIGHT, LOW);
+	} else {
+		digitalWrite(HEADLIGHT, HIGH);
+	}
+
+	if ((btc_config.auto_b) && (analogRead(LIGHT_SENSOR) > btc_config.lux_light_on)) {	// Следилка за фарой
+		digitalWrite(DISPLAY_LIGHT, LOW);
+}
+
+unsigned int key_pressed(bool wait_keys /*Надо ли ожидать кнопку бесконечно*/) {	// Определение нажатой кнопки
+	int		key,
+			delay_time	= 0;	// Время зажатия кнопки
+
+	while (sys_watch()) {
+
+		key	= analogRead(ACTION_BUTTON);
+
+		if ((key >= btc_config.button_ok - 5) && (key <= btc_config.button_ok + 5)) {
+			key = btc_config.button_ok;
+			break;
+		} else if ((key >= btc_config.button_up - 5) && (key <= btc_config.button_up + 5)) {
+			key = btc_config.button_up;
+			break;
+		} else if ((key >= btc_config.button_down - 5) && (key <= btc_config.button_down + 5)) {
+			key = btc_config.button_down;
+			break;
+		} else if ((key >= btc_config.button_signal - 5) && (key <= btc_config.button_signal + 5)) {
+			key = btc_config.button_signal;
+			break;
+		}
+
+		if (!wait_keys)
+			break;
+	}
+
+	while ((analogRead(ACTION_BUTTON) > 5) && (delay_time < SWITCH_NEXT)) {	// Ожидание зажатия
+		delay(1);
+		delay_time++;
+	}
+
+	return key;
+}


Modify touch switch reading to use an internal pull-up


Last of updates to arduino code

Last of updates to arduino code

Organized code into functions, and changed the way config changes are
sent/executed on the arduino.

--- Arduino/btCarBot/btCarBot.new.ino
+++ Arduino/btCarBot/btCarBot.new.ino
@@ -29,6 +29,7 @@
 // o = option-set mode

 char mode = 'd';
+char option;

 void setup() {
 	// Open serial communications and wait for port to open:
@@ -46,28 +47,35 @@

 void loop() {

-	byte read = 0;
-	if (mySerial.available()) read = mySerial.read();
+	// Don't do anything unless there was input from the user
+	if (mySerial.available()) {

-	switch (mode) {
+		byte read = mySerial.read();
+		Serial.write(read);

-		// Drive (d) mode by default
-		case 'd': driveCommand(read); break;
-		case 'c':
-		case 'o': config(read) break;
-		// If something weird happens and mode isn't a valid
-		// value, put everything back into drive mode
-		default: mode = 'd';
+		// If user presses c, enter config mode and go to next loop of void loop()
+		if(read == 'c') {
+			mode = 'c';
+			return;
+		}

+		switch (mode) {
+			case 'd': driveCommand(read); break;
+			case 'o': optionSet(read); break;
+			case 'c': config(read); break;
+		}
 	}
+}

-	switch (read) {
+void optionSet(byte read) {
+	if(option == 'v') if (read > 0 && read < 255) velocity = read;
+
+	mode = 'd'; // Go back to drive mode once the selected option is set
+}

-		default: {
-			Serial.print("Set speed: ");
-			if (read > 0 && read < 255) velocity = read;
-		} break;
-	}
+void config(byte read) {
+	option = read; // Keep track of what option is going to be set
+	mode = 'o'; // Put the program into option-set mode
 }

 void driveCommand(byte read) {


Updates to I2C test program. Measures everything successfully and runs motor well. Sweet.

--- arduino/I2CControl/I2CControl.ino
+++ arduino/I2CControl/I2CControl.ino
@@ -45,7 +45,7 @@
 // temp. for nominal resistance (almost always 25 C)
 #define TEMPERATURENOMINAL 25
 // The beta coefficient of the thermistor (usually 3000-4000)
-#define BCOEFFICIENT 3950
+#define BCOEFFICIENT 3900
 // the value of the 'other' resistor
 #define SERIESRESISTOR 3300

@@ -122,23 +122,28 @@
   static uint32_t writeTimer = 0;
   static uint32_t readTimer = 0;

+  static int16_t signal = 0;
+
   if ( millis() - writeTimer > 100 ) {
     writeTimer = millis();
-
-    static int16_t signal = 0;
-    static int16_t increment = 50;
+
+    static int16_t increment = 200;
+
+    if (Serial.available()) {
+      signal = Serial.parseInt();
+    }

     //Serial.print("Sending ");Serial.print(signal);
     setESC(I2C_ADDR,signal);

-    signal += increment;
+    /*signal += increment;

-    if ( abs(signal) > 6000 ) {
+    if ( abs(signal) > 32500 ) {
       increment = -increment;
-    }
+    }*/
   }

-  if ( micros() - readTimer > 1000000 ) {
+  if ( micros() - readTimer > 100000 ) {
     uint32_t dt = micros() - readTimer;

     readTimer = micros();
@@ -157,10 +162,20 @@
     steinhart = 1.0 / steinhart;                 // Invert
     steinhart -= 273.15;                         // convert to C

-    Serial.print("RPM:  ");Serial.println(rpm/(dt/1000000.0f)*60/6);
+    static float current;
+
+    current = current*0.9 + (float(curr)-33344)/65535.0f*5*14.706*0.1;
+
+    Serial.write(27);       // ESC command
+    Serial.print("[2J");    // clear screen command
+    Serial.write(27);
+    Serial.print("[H");     // cursor to home command
+    Serial.print("Thro: ");Serial.println(signal);
+    Serial.print("RPM:  ");Serial.println(int(rpm/(dt/1000000.0f)*60/6));
     Serial.print("VBat: ");Serial.println(float(vbat)/65536*5*6.45);
     Serial.print("Temp: ");Serial.println(steinhart);
-    Serial.print("Curr: ");Serial.println((float(curr)-32768)/65536*5*14.706);
+    Serial.print("Curr: ");Serial.println(current);
+    Serial.print("Powr: ");Serial.println(current*float(vbat)/65536*5*6.45);
     Serial.println("---------------------");
   }
 }


added a better configurarion string for the line following example

--- libraries/Robot_Control/examples/explore/R10_Rescue/R10_Rescue.ino
+++ libraries/Robot_Control/examples/explore/R10_Rescue/R10_Rescue.ino
@@ -53,8 +53,10 @@
   Robot.text("Start", 5, 5);

   // use this to calibrate the line following algorithm
+  // uncomment one or the other to see the different behaviors of the robot
+  // Robot.lineFollowConfig(11, 5, 50, 10);
   Robot.lineFollowConfig(14, 9, 50, 10);
-
+
   // run the rescue sequence
   rescueSequence();
   Robot.text("Found obstacle", 5, 12);


Delete platform3.ino

Delete platform3.ino

--- home/harland/platform3.ino
+++ home/harland/platform3.ino
@@ -1,380 +0,0 @@
-#include <Servo.h>
-
-/*
-for azul mobile platform running on mega board
-which has:
-parallax pings
-i/r sensors
-servo motor drivers
-eacon sensor
-compass HMC5883L
-april 20,2016
- */
-
-#include <Wire.h>
-#include <SPI.h>
-#include <HMC5883L.h>
-HMC5883L compass;
-#include <Servo.h>
-Servo servoR; // create servo object to control a servo
-Servo servoL; // create servo object to control a servo
-#include <SoftwareSerial.h>
-SoftwareSerial LedSerial(12, 13); // RX2=12 and TX2=13   RX3=63 and TX3=64  RX1=45 and TX1=46
-
-
-String serdata = "";
-// I/R sensors data  turns out this data is not very good
-int distcen = 0;
-int distright = 0;
-int distleft = 0;
-// ping sensors left and right  info very good
-int DistPingRight = 0;
-int DistPingLeft = 0;
-// input routine
-String cmd;
-String sBuffer = "";
-String sResp = "?";
-// motors are controlled like servo
-int OldSpeed = 90;   // storage of last speed for stopping
-int speed = 90;
-int wheeloffsetR = 0;   // try to adjust for different speed motors
-int wheeloffsetL = 0;
-
-int AnalogPinCount = 5;     // number of channels in use
-const int AnalogPins [] =
-{
-  0,  // back center i/r sensor higher number is closer above 400 around 12 inches
-  1,  // front right i/r sensor
-  2,  // front left  i/r sensor
-  3,  // battery voltage 14.8v= 1008cnt and 12.7v=865cnt
-  4,
-  5,
-  6,
-  7,
-  8,
-  9,
-  10,
-  11,
-  12,
-  13,
-};
-
-int OutputPinCount = 4;     // number of channels in use
-const int MaOutputPins [] =
-{
-  4,   // servo motor wheel right
-  2,   // servo motor wheel left
-  3,
-  5,
-  6,
-  7,   // ping right rear
-  8,   // ping left rear
-  9,
-  10,
-  11,  // ping center front
-  12,  // ping left front
-  13,  // ping right front
-};
-
-int PingPinCount = 5;     // number of channels in use
-const int PingPin [] =
-{
-  7,   // ping rear right
-  8,   // ping rear left
-  11,  // ping front center
-  12,  // ping front left
-  13,  // ping front right
-};
-
-
-// could calculate this by #define OutPinCount (sizeof (MaOutputPins) / sizeof (MaOutputPins [0]))
-
-void setup()
-{
-  int i;
-  for (i = 0; i < OutputPinCount; i++)
-  {
-    pinMode (MaOutputPins [i], OUTPUT);     // set to output mode
-    digitalWrite (MaOutputPins [i], LOW);  // set chip enable off
-  }
-// setup SPI channel
-// SPI.begin();         		            // wake up the SPI bus.
-// SPI.setBitOrder(MSBFIRST);  	      // wants data most significant byte first
-// SPI.setDataMode(SPI_MODE3);          //  Set for clock rising edge
-// SPI.setClockDivider(SPI_CLOCK_DIV64);    //  Set clock divider (optional)
-// servo setup pins
-  servoR.attach(MaOutputPins [0]);
-  servoL.attach(MaOutputPins [1]);
-  Wire.begin();                        // Start the I2C interface.
-  compass = HMC5883L();                // Construct a new HMC5883 compass.
-  setupHMC5883L();                    //setup the HMC5883L
-  LedSerial.begin(2400);            // separate board that controls lights
-  LedSerial.print( "!DC16");     // all leds off board address
-  LedSerial.print( B00 );     // statusLo controls OUT1..OUT8, statusHi controls OUT9..OUT16  1 bit = On, 0 bit = Off
-  LedSerial.println( "X");     // end of string
-  Serial.begin (57600);             // setup Serial port at 57,600 baud
-  Serial.println(" platform Ver. 4-20-2016");
-}
-
-// main loop only watches serial input
-void loop()
-{
-  char c;
-  if (Serial.available () > 0)
-  {
-    while (Serial.available () > 0)
-    {
-      delay (10);
-      c = Serial.read ();
-      if (c == '\r')
-      {
-        ProcessCommand ();
-        sBuffer = "";
-        continue;
-      }
-      sBuffer += c;             // make string
-    }
-  }
-//  delay (50);
-}
-
-void ProcessCommand ()
-{
-  sResp = " ";                    // may use this later
-  if (sBuffer.length () > 0)
-  {
-    sBuffer.toUpperCase ();
-//    Serial.println(sBuffer);
-    switch (sBuffer [0])            // look at first character in string
-    {
-      case 'A':
-        ReadAnalog();
-        delay(1);
-        break;
-      case 'P':
-        ReadPing();
-        delay(1);
-        break;
-      case 'C':
-        ReadCompass();
-        delay(1);
-        break;
-      case 'F':         // go forward
-        ProcessRestCmd (sBuffer.substring (1));
-        if (speed > 55){
-          Serial.println("wrong spd");
-        }
-        MrtFwd( speed );
-        break;
-      case 'B':         // go backward
-        ProcessRestCmd (sBuffer.substring (1));
-        if (speed > 55){
-          Serial.println("wrong spd");
-        }
-        MrtRev( speed );
-        break;
-      case 'R':         // turn right
-        ProcessRestCmd (sBuffer.substring (1));
-        if (speed > 55){
-          Serial.println("wrong spd");
-        }
-        TurnRight( speed );
-        break;
-      case 'L':         // turn left
-        ProcessRestCmd (sBuffer.substring (1));
-       if (speed > 55){
-          Serial.println("wrong spd");
-        }
-        TurnLeft( speed );
-        break;
-      case 'M':         // move forward looking at sensors
-        ProcessRestCmd (sBuffer.substring (1));
-       if (speed > 55){
-          Serial.println("wrong spd");
-        }
-        MoveFwd( speed );
-        break;
-      case 'S':
-        MrtStop();
-        break;
-     case '?':
-        Serial.println("Help  ver. 04-20-2016");
-        Serial.println("P ping distance readings ");
-        Serial.println("A analog readings ");
-        Serial.println("C compass not working ");
-        Serial.println("F forward motors 0 to 50 ");
-        Serial.println("B reverse motors 0 to 50 ");
-        Serial.println("R turn right 0 to 50");
-        Serial.println("L turn left 0 to 50");
-        break;
-    }
-//  Serial.println (sResp);           // Prompts
-  Serial.println (">");
-  }
-}
-
-void ProcessRestCmd (String NumCmd)
-{
-  long speed1;
-  speed1 = NumCmd.toInt ();
-  speed = (speed1);                    // save number int
-//  Serial.println(speed);
-}
-
-
-void ReadAnalog(){
- int reading;                        // reading from a to d
- float voltage;                       // voltage calculated from a to d
- for (int x=0; x < AnalogPinCount; x++){
-   reading = analogRead(AnalogPins[x]);        // get raw number
-   Serial.print("A");
-   Serial.print(x);
-   Serial.print("=");
-   Serial.print(reading);         // show raw number
-   Serial.print(",");
-//   Serial.print("cnt, ");
-//   voltage = reading * 5.0;
-//   voltage /= 1024.0;
-//   voltage = 0.00488 * reading;        // 5 / 1024 = .00488
-//   Serial.print(voltage);         // show voltage calculated
-//   Serial.print("v, ");
- }
- Serial.println();
-}
-
-void ReadPing(){
-  long duration, inches, cm;
-
- for (int x=0; x < PingPinCount; x++){
-  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
-  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
-  pinMode(PingPin[x], OUTPUT);
-  digitalWrite(PingPin[x], LOW);
-  delayMicroseconds(2);
-  digitalWrite(PingPin[x], HIGH);
-  delayMicroseconds(5);
-  digitalWrite(PingPin[x], LOW);
-  // The same pin is used to read the signal from the PING))): a HIGH
-  // pulse whose duration is the time (in microseconds) from the sending
-  // of the ping to the reception of its echo off of an object.
-  pinMode(PingPin[x], INPUT);
-  duration = pulseIn(PingPin[x], HIGH);
-  // convert the time into a distance
-  inches = microsecondsToInches(duration);
-  Serial.print("P");
-  Serial.print(x);
-  Serial.print("=");
-  Serial.print(inches);
-  Serial.print(",");
-//  Serial.print("in, ");
- }
-  Serial.println();
-}
-
-long microsecondsToInches(long microseconds) {
-  // According to Parallax's datasheet for the PING))), there are
-  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
-  // second).  This gives the distance travelled by the ping, outbound
-  // and return, so we divide by 2 to get the distance of the obstacle.
-  return microseconds / 74 / 2;
-}
-
-void ReadCompass(){
-  MagnetometerScaled scaled = compass.ReadScaledAxis();
-  int MilliGauss_OnThe_XAxis = scaled.XAxis;
-  float heading = atan2(scaled.YAxis, scaled.XAxis);
-  float declinationAngle = 0.0457;
-  heading += declinationAngle;
-  if(heading < 0)
-    heading += 2*PI;
-  if(heading > 2*PI)
-    heading -= 2*PI;
-  float headingDegrees = heading * 180/M_PI;
-//  Output(headingDegrees);
-  Serial.println(headingDegrees);
-  delay(500);     //jhs 5sec
-}
-
-void Output(float headingDegrees)
-{
-   Serial.print("Head Deg=");
-   Serial.print(headingDegrees);
-   Serial.println("\t");
-}
-
-void setupHMC5883L(){
-  //Setup the HMC5883L, and check for errors
-  int error;
-  error = compass.SetScale(1.3); //Set the scale of the compass.
-  if(error != 0) Serial.println(compass.GetErrorText(error)); //check if there is an error, and print if so
-
-  error = compass.SetMeasurementMode(Measurement_Continuous); // Set the measurement mode to Continuous
-  if(error != 0) Serial.println(compass.GetErrorText(error)); //check if there is an error, and print if so
-}
-
-void MrtStop(){                     // motors stop at 90
-      while(OldSpeed > 90){         // want slow stop
-        speed = OldSpeed - 1;
-        OldSpeed = speed;
-        servoR.write(speed);
-        servoL.write(speed);
-        delay(50);
-//        Serial.println(speed);   // make sure working right
-      }
-      while(OldSpeed < 90){
-        speed = OldSpeed + 1;
-        OldSpeed = speed;
-        servoR.write(speed);
-        servoL.write(speed);
-        delay(50);
-//        Serial.println(speed);   // make sure working right
-      }
-      servoR.write(90);           // all stop for sure
-      servoL.write(90);
-}
-
-void MrtFwd( int speed ){
-     OldSpeed = speed + 90;           //storing for stopping
-     servoR.write(90 + speed + wheeloffsetR);   // try to adjust for different speed motors
-     servoL.write(90 + speed + wheeloffsetL);
-}
-
-void MrtRev( int speed ){
-     OldSpeed = 90 - speed;
-     servoR.write(90 - speed + wheeloffsetR);
-     servoL.write(90 - speed + wheeloffsetL);
-     int ir0=100;
-     while( ir0<400 ){
-        ir0 = analogRead(AnalogPins[0]);        // check i/r sensor back
-        delay(50);
-     }
-//      ReadAnalog();        // just checking to see if working
-      MrtStop();
-}
-
-void TurnLeft( int speed ){
-     servoR.write(90 - speed);
-     servoL.write(speed + 90);
-}
-
-void TurnRight( int speed ){
-     servoR.write(speed + 90);
-     servoL.write(90 - speed);     // reverse direction
-}
-
-void MoveFwd( int speed ){
-     OldSpeed = speed + 90;           //storing for stopping
-     servoR.write(90 + speed + wheeloffsetR);
-     servoL.write(90 + speed + wheeloffsetL);
-     int ir1=100;
-     int ir2=100;
-      while( (ir1<400) && (ir2<400) ){
-        ir1 = analogRead(AnalogPins[1]);        // check i/r sensors front 1,2
-        delay(30);
-        ir2 = analogRead(AnalogPins[2]);
-        delay(30);
-     }
-//      ReadAnalog();        // just checking to see if working
-      MrtStop();
-}
-


Corrected mesh setup sequence

Corrected mesh setup sequence

--- Code/Examples/NetworkV1/ZeroConfRouter/ZeroConfRouter.ino
+++ Code/Examples/NetworkV1/ZeroConfRouter/ZeroConfRouter.ino
@@ -142,10 +142,20 @@
 	trace.begin(&null_device, NULL);
 #endif

+	zeroConfListener.init();
+
+	trace << PSTR("Waiting for configuration...") << endl;
 	//Allow some time for initial configuration
 	bool reconfigured = processConfigSequence();
 	UNUSED(reconfigured);

+	mesh.setChannel(configuration.nwkconfig.channel);
+	mesh.setNetworkID(configuration.nwkconfig.nwkid);
+	mesh.setNodeID(configuration.nwkconfig.nodeid);
+
+	trace << PSTR("Configuration done.") << endl;
+	//Flush all chars before disabling UART
+	uart.flush();
 	//Disable UART when reconfigured. Blink differently if reconfigured
 	uart.end();
 	LED_BLINK(false, reconfigured ? 2000 : 500);


Colors definition

Colors definition

--- arduino/sketch.ino
+++ arduino/sketch.ino
@@ -15,7 +15,7 @@

 void loop() {
 	/* Get that for later :) */
-/* 	StaticJsonBuffer<200> jsonBuffer;
+	/* 	StaticJsonBuffer<200> jsonBuffer;
 	char json[] = "{\"round\": {\"phase\": \"live\",\"bomb\": \"planted\"}}";
 	JsonObject& root = jsonBuffer.parseObject(json);

@@ -23,11 +23,12 @@
 		Serial.println("parseObject() failed");
 		return;
 	}
-
+
 	const char* bombStatus = root["round"]["bomb"];
 	if(bombStatus == "planted") {
 	}
 	Serial.println(bombStatus); */
+	bombColor();
 }

 void initSerial() {
@@ -36,4 +37,30 @@
 	  ;
 	}
 	Serial.println("Serial ready");
+}
+
+void setColor(int red, int green, int blue) {
+  analogWrite(REDPIN, red);
+  analogWrite(GREENPIN, green);
+  analogWrite(BLUEPIN, blue);
+}
+
+void counterColor() {
+	setColor(20,36,214);
+}
+
+void terroristColor() {
+	setColor(244,144,4);
+}
+
+void deadColor() {
+	setColor(171,3,142);
+}
+
+void bombColor() {
+	setColor(254,0,0);
+}
+
+void fadeTo(int red, int green, int blue) {
+
 }


Code cleanup, added comments and removed cruft.

--- shofanduino2/shofanduino2.ino
+++ shofanduino2/shofanduino2.ino
@@ -1,4 +1,3 @@
-//#include <Time.h>
 #include <DHT22.h>

 #define DHT22_PIN 6
@@ -110,6 +109,10 @@

 void loop() {
   getValues();
+
+  /*
+   * Calculate limits
+   */

   // clamp the envelope min/max, decay otherwise
   if (env_min > humidity) {
@@ -132,6 +135,9 @@
   thresholdLow = env_min + (env_max - env_min) / 20.0f;
   thresholdHigh = env_min + (env_max - env_min) / 2.0f;

+  /*
+   * Check state
+   */
   int new_state = FAN_NOCHANGE;
   if (humidity < thresholdLow) {
     new_state = FAN_OFF;
@@ -176,6 +182,10 @@
       break;
   }

+  /*
+   * Output for debugging/graphing
+   */
+
   // print out the values for debugging/plotting
   Serial.print("humidity = ");
   Serial.print(humidity, 1);


Delete Esp8266GatewayPimatic-1.5.ino

Delete Esp8266GatewayPimatic-1.5.ino

--- Esp8266GatewayPimatic-1.5.ino
+++ Esp8266GatewayPimatic-1.5.ino
@@ -1,360 +0,0 @@
-/**
- * The MySensors Arduino library handles the wireless radio link and protocol
- * between your home built sensors/actuators and HA controller of choice.
- * The sensors forms a self healing radio network with optional repeaters. Each
- * repeater and gateway builds a routing tables in EEPROM which keeps track of the
- * network topology allowing messages to be routed to nodes.
- *
- * Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
- * Copyright (C) 2013-2015 Sensnology AB
- * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
- *
- * Documentation: http://www.mysensors.org
- * Support Forum: http://forum.mysensors.org
- *
- * 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.
- *
- *******************************
- *
- * REVISION HISTORY
- * 1.2 HvdW - add REST-API functionality to push sensor data to pimatic
- * 1.1 HvdW - add mDNS, static ip
- * Version 1.0 - Henrik EKblad
- * Contribution by a-lurker and Anticimex,
- * Contribution by Norbert Truchsess <norbert.truchsess@t-online.de>
- * Contribution by Ivo Pullens (ESP8266 support)
- *
- * DESCRIPTION
- * The EthernetGateway sends data received from sensors to the WiFi link.
- * The gateway also accepts input on ethernet interface, which is then sent out to the radio network.
- *
- * VERA CONFIGURATION:
- * Enter "ip-number:port" in the ip-field of the Arduino GW device. This will temporarily override any serial configuration for the Vera plugin.
- * E.g. If you want to use the defualt values in this sketch enter: 192.168.178.66:5003
- *
- * LED purposes:
- * - To use the feature, uncomment WITH_LEDS_BLINKING in MyConfig.h
- * - RX (green) - blink fast on radio message recieved. In inclusion mode will blink fast only on presentation recieved
- * - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly
- * - ERR (red) - fast blink on error during transmission error or recieve crc error
- *
- * See http://www.mysensors.org/build/ethernet_gateway for wiring instructions.
- * The ESP8266 however requires different wiring:
- * nRF24L01+  ESP8266
- * VCC        VCC
- * CE         GPIO4
- * CSN/CS     GPIO15
- * SCK        GPIO14
- * MISO       GPIO12
- * MOSI       GPIO13
- *
- * Not all ESP8266 modules have all pins available on their external interface.
- * This code has been tested on an ESP-12 module.
- * The ESP8266 requires a certain pin configuration to download code, and another one to run code:
- * - Connect REST (reset) via 10K pullup resistor to VCC, and via switch to GND ('reset switch')
- * - Connect GPIO15 via 10K pulldown resistor to GND
- * - Connect CH_PD via 10K resistor to VCC
- * - Connect GPIO2 via 10K resistor to VCC
- * - Connect GPIO0 via 10K resistor to VCC, and via switch to GND ('bootload switch')
- *
-  * Inclusion mode button:
- * - Connect GPIO5 via switch to GND ('inclusion switch')
- *
- * Hardware SHA204 signing is currently not supported!
- *
- * Make sure to fill in your ssid and WiFi password below for ssid & pass.
- */
-#define NO_PORTB_PINCHANGES
-
-#include <SPI.h>
-
-#include <MySigningNone.h>
-#include <MySigningAtsha204Soft.h>
-#include <MyTransportNRF24.h>
-#include <MyTransportRFM69.h>
-#include <EEPROM.h>
-#include <MyHwESP8266.h>
-#include <ESP8266WiFi.h>
-
-#include <MyParserSerial.h>
-#include <MySensor.h>
-#include <stdarg.h>
-#include "GatewayUtil.h"
-
-#include <ESP8266mDNS.h>
-#include <Base64.h>
-
-#define MY_DEBUG
-
-
-///////////// WLAN settings ////////////
-const char *ssid =  "SSID";    // cannot be longer than 32 characters!
-const char *pass =  "SecretPassword"; //
-String espName    = "esp8266gateway";  // for avahi/bonjour name => gives in this example esp8266gateway.local
-
-///////////// pimatic settings ////////////
-String pim_host = "192.168.144.128";   // your pimatic server
-const int pim_port = 80;                // your pimatic server port
-String pim_user =  "apiposter";             // the user you use to read from & write to pimatic
-String pim_pass =  "ap1p0ster";             // The password for that pim_user
-
-char authVal[40];
-char authValEncoded[40];
-
-///////////// Configure a static ip address ////////////
-#define DEFAULT_USE_STATIC_IP   true           // true or false enabled or disabled set static IP
-IPAddress ip(192,168,144,245);
-IPAddress gateway(192,168,144,1);
-IPAddress subnet(255,255,255,0);
-
-
-#define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled
-#define INCLUSION_MODE_PIN  5 // Digital pin used for inclusion mode button
-
-#define RADIO_CE_PIN        4   // radio chip enable
-#define RADIO_SPI_SS_PIN    15  // radio SPI serial select
-
-#ifdef WITH_LEDS_BLINKING
-#define RADIO_ERROR_LED_PIN 7  // Error led pin
-#define RADIO_RX_LED_PIN    8  // Receive led pin
-#define RADIO_TX_LED_PIN    9  // the PCB, on board LED
-#endif
-
-
-// NRFRF24L01 radio driver (set low transmit power by default)
-MyTransportNRF24 transport(RADIO_CE_PIN, RADIO_SPI_SS_PIN, RF24_PA_LEVEL_GW);
-//MyTransportRFM69 transport;
-
-
-// Message signing driver (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h)
-#ifdef MY_SIGNING_FEATURE
-MySigningNone signer;
-//MySigningAtsha204Soft signer;
-#endif
-
-// Hardware profile
-MyHwESP8266 hw;
-
-// Construct MySensors library (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h)
-// To use LEDs blinking, uncomment WITH_LEDS_BLINKING in MyConfig.h
-MySensor gw(transport, hw
-#ifdef MY_SIGNING_FEATURE
-    , signer
-#endif
-#ifdef WITH_LEDS_BLINKING
-  , RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN
-#endif
-  );
-
-
-#define IP_PORT 5003         // The port you want to open
-#define MAX_SRV_CLIENTS 5    // how many clients should be able to telnet to this ESP8266
-
-// a R/W server on the port
-static WiFiServer server(IP_PORT);
-static WiFiClient clients[MAX_SRV_CLIENTS];
-static bool clientsConnected[MAX_SRV_CLIENTS];
-static inputBuffer inputString[MAX_SRV_CLIENTS];
-
-// Activate mDNS
-MDNSResponder   mdns;
-
-String ClientIP;
-// send data
-WiFiClient client;
-
-
-#define ARRAY_SIZE(x)  (sizeof(x)/sizeof(x[0]))
-
-
-void output(const char *fmt, ... )
-{
-  char serialBuffer[MAX_SEND_LENGTH];
-  va_list args;
-  va_start (args, fmt );
-  vsnprintf_P(serialBuffer, MAX_SEND_LENGTH, fmt, args);
-  va_end (args);
-  Serial.print(serialBuffer);
-  for (uint8_t i = 0; i < ARRAY_SIZE(clients); i++)
-  {
-    if (clients[i] && clients[i].connected())
-    {
-//       Serial.print("Client "); Serial.print(i); Serial.println(" write");
-       clients[i].write((uint8_t*)serialBuffer, strlen(serialBuffer));
-    }
-  }
-}
-
-void incomingMessageESP(const MyMessage &message) {
-  String yourdata;
-   char yourvariable[10];
-
-  // Pass along the message from sensors to serial line
-  serial(PSTR("%d;%d;%d;%d;%d;%s\n"),message.sender, message.sensor, mGetCommand(message), mGetAck(message), message.type, message.getString(convBuf));
-  Serial.print("Node-Sensor (variable to use in pimatic) ");Serial.print(message.sender);Serial.print("-");Serial.print(message.sensor);Serial.print("; Value ");Serial.println(message.getString(convBuf));
-
-  char host_char_array[pim_host.length()+1];
-  pim_host.toCharArray(host_char_array,pim_host.length()+1);
-
-  if (!client.connect(host_char_array, pim_port)) {
-    Serial.println("connection failed");
-    return;
-  }
-
-  // calculate Base64Login
-  memset(authVal,0,40);
-  (pim_user + String(":") + pim_pass).toCharArray(authVal, 40);
-  memset(authValEncoded,0,40);
-  base64_encode(authValEncoded, authVal, (pim_user + String(":") + pim_pass).length());
-
-
-  //Send Value received from node
-  yourdata = "{\"type\": \"value\", \"valueOrExpression\": \"" + String(message.getString(convBuf)) + "\"}";
-  sprintf(yourvariable, "%d-%d",message.sender,message.sensor);
-
-    client.print("PATCH /api/variables/");
-    client.print(yourvariable);
-    client.print(" HTTP/1.1\r\n");
-    client.print("Authorization: Basic ");
-    client.print(authValEncoded);
-    client.print("\r\n");
-    client.print("Host: " + pim_host +"\r\n");
-    client.print("Content-Type:application/json\r\n");
-    client.print("Content-Length: ");
-    client.print(yourdata.length());
-    client.print("\r\n\r\n");
-    client.print(yourdata);
-
-}
-
-
-void checkwifi(){
-  //check if connected to wifi - if not connect
-  if (WiFi.status() != WL_CONNECTED){
-    (void)WiFi.begin(ssid, pass);
-    while (WiFi.status() != WL_CONNECTED){
-      delay(500);
-      Serial.print(".");
-    }
-    // When connected, and when DEFAULT_USE_STATIC_IP is set to true, assign a static ip
-    if (DEFAULT_USE_STATIC_IP == true){
-      WiFi.config(ip, gateway, subnet);
-    }
-  Serial.println("Connected!");  Serial.print("IP: "); Serial.println(WiFi.localIP());  Serial.flush();
-  }
-}
-
-
-void setup()
-{
-  // Setup console
-  hw_init();
-
-  Serial.println(); Serial.println();
-  Serial.println("ESP8266 MySensors Gateway with pimatic interface");
-  Serial.print("Connecting to "); Serial.println(ssid);
-
-  checkwifi();
-
-  // Start mDNS service
-  if (!mdns.begin(espName.c_str(), WiFi.localIP())) {
-    Serial.println("Error setting up MDNS responder!");
-    while(1) {
-      delay(1000);
-    }
-  }
-
-  setupGateway(INCLUSION_MODE_PIN, INCLUSION_MODE_TIME, output);
-
-  // Initialize gateway at maximum PA level, channel 70 and callback for write operations
-  //gw.begin(incomingMessage, 0, true, 0);
-
-  gw.begin(incomingMessageESP, 0, true, 0);
-
-  // start listening for clients
-  server.begin();
-  server.setNoDelay(true);
-}
-
-
-void loop() {
-  gw.process();
-
-  checkButtonTriggeredInclusion();
-  checkInclusionFinished();
-
-  // Go over list of clients and stop any that are no longer connected.
-  // If the server has a new client connection it will be assigned to a free slot.
-  bool allSlotsOccupied = true;
-  for (uint8_t i = 0; i < ARRAY_SIZE(clients); i++)
-  {
-    if (!clients[i].connected())
-    {
-      if (clientsConnected[i])
-      {
-        Serial.print("Client "); Serial.print(i); Serial.println(" disconnected");
-        clients[i].stop();
-      }
-      //check if there are any new clients
-      if (server.hasClient())
-      {
-        clients[i] = server.available();
-        inputString[i].idx = 0;
-        Serial.print("Client "); Serial.print(i); Serial.println(" connected");
-        output(PSTR("0;0;%d;0;%d;Gateway startup complete.\n"),  C_INTERNAL, I_GATEWAY_READY);
-      }
-    }
-    bool connected = clients[i].connected();
-    clientsConnected[i] = connected;
-    allSlotsOccupied &= connected;
-  }
-  if (allSlotsOccupied && server.hasClient())
-  {
-    //no free/disconnected spot so reject
-    Serial.println("No free slot available");
-    WiFiClient c = server.available();
-    c.stop();
-  }
-
-  // Loop over clients connect and read available data
-  for (uint8_t i = 0; i < ARRAY_SIZE(clients); i++)
-  {
-    while(clients[i].connected() && clients[i].available())
-    {
-      char inChar = clients[i].read();
-      if ( inputString[i].idx < MAX_RECEIVE_LENGTH - 1 )
-      {
-        // if newline then command is complete
-        if (inChar == '\n')
-        {
-          // a command was issued by the client
-          // we will now try to send it to the actuator
-          inputString[i].string[inputString[i].idx] = 0;
-
-          // echo the string to the serial port
-          Serial.print("Client "); Serial.print(i); Serial.print(": "); Serial.println(inputString[i].string);
-
-          parseAndSend(gw, inputString[i].string);
-
-          // clear the string:
-          inputString[i].idx = 0;
-          // Finished with this client's message. Next loop() we'll see if there's more to read.
-          break;
-        } else {
-         // add it to the inputString:
-         inputString[i].string[inputString[i].idx++] = inChar;
-        }
-      } else {
-        // Incoming message too long. Throw away
-        Serial.print("Client "); Serial.print(i); Serial.println(": Message too long");
-        inputString[i].idx = 0;
-        // Finished with this client's message. Next loop() we'll see if there's more to read.
-        break;
-      }
-    }
-  }
-}
-
-


Use powerOFF on powerOFF example

Use powerOFF on powerOFF example

--- examples/Basics/PowerOFF/PowerOFF.ino
+++ examples/Basics/PowerOFF/PowerOFF.ino
@@ -18,7 +18,7 @@
 void loop() {

   if(M5.BtnA.wasPressed()) {
-    M5.Power.deepSleep();
+    M5.Power.powerOFF();
   }

   M5.update();


Reset presets in NOKO.ino

Reset presets in NOKO.ino

--- src/V10/Deutsch/NOKO/NOKO.ino
+++ src/V10/Deutsch/NOKO/NOKO.ino
@@ -109,7 +109,6 @@
 #define vol_mp3       30  // JQ6500 volume 0-30
 #define vol_radio     10  // Si4703 volume 0-15
 #define def_sysinfo       // Sysinfo menu. Comment out for additional 640 bytes
-#define busy_analog     // Set if reading the busy signal analog via A1

 // Choose your voice set
 //#define voice_set_111   // Old set with 111 files


redistributed its pieces elsewhere

redistributed its pieces elsewhere

--- pinTest.ino
+++ pinTest.ino
@@ -1,28 +0,0 @@
-
-/* @param mode shoudl be one of:: INPUT, INPUT_PULLUP, and OUTPUT */
-template <unsigned arduinoNumber,unsigned mode,unsigned polarity=digitalHigh> class Pin {
-public:
-  Pin(){
-    pinMode(arduinoNumber,mode);
-  }
-  volatile operator bool()const{
-    return digitalRead(arduinoNumber)==polarity;
-  }
-  bool operator =(bool value){
-    digitalWrite(arduinoNumber,value?polarity:digitalHigh+digitalLow-polarity);
-  }
-}
-
-/** pin 13 is attached to the high side of an LED */
-Pin<13,0,digitalHigh> LED;//static constructors run just before main() is called, which in turn calls setup and loop.
-Pin(12,1,digitalLow> button;
-
-void setup() {
-  // put your setup code here, to run once:
-
-}
-
-void loop() {
-  // put your main code here, to run repeatedly:
-  LED=!button;
-}


Fixed issues with delivery of messages

Fixed issues with delivery of messages

--- SensorReader/SensorReader.ino
+++ SensorReader/SensorReader.ino
@@ -18,20 +18,24 @@
 // room temperature in Celcius
 const float baselineTemp = 30.0;

-char ssid[] = "NETGEAR67";     //  your network SSID (name)
-char pass[] = "huskywater261";    // your network password
+//char ssid[] = "NETGEAR67";     //  your network SSID (name)
+//char pass[] = "huskywater261";    // your network password
+char ssid[] = "AndroidHotspot4559";     //  your network SSID (name)
+char pass[] = "64a5676f2d4c";    // your network password
 int status = WL_IDLE_STATUS;     // the Wifi radio's status

 //#define MQTT_SERVER "192.168.0.8"
 byte mac[]    = {  0x90, 0xA2, 0xDA, 0x0E, 0x07, 0x18 };
-byte serverRabbit[] = { 192, 168, 0, 2 };//192.168.0.8
-byte ip[]     = { 192, 168, 0, 4 };
+//byte serverRabbit[] = { 192, 168, 0, 2 };//192.168.0.8
+byte serverRabbit[] = { 104, 131, 80, 167 };
+//byte serverRabbit[] = { 192, 168, 43, 246 };
+//byte ip[]     = { 192, 168, 0, 4 };
 char clientName[] = "clientA";
 char user[] = "mqtt";
 char pwd[] = "mqtt";
 int port = 1883;
-int tiltState;
-//int previousTiltState = 2;
+int countTempInterval = 0;
+int previousTiltState = 2;

 //Time on arduino http://playground.arduino.cc/Code/DateTime

@@ -41,47 +45,32 @@
 #define MODE_OFF    0  // not sensing light, LED off
 #define MODE_ON     1  // not sensing light, LED on
 #define MODE_SENSE  2  // sensing light, LED controlled by software
-int senseMode = 0;
-char message_buff[100];
 //setup MQTT
 WiFiClient wifiClient;
 //MQTT
-PubSubClient client(serverRabbit, port, callback, wifiClient);
+PubSubClient client(serverRabbit, port, callbackFunction, wifiClient);
 MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
-// Number of known default keys (hard-coded)
-// NOTE: Synchronize the NR_KNOWN_KEYS define with the defaultKeys[] array
-#define NR_KNOWN_KEYS   8
-// Known keys, see: https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys
-byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] =  {
-    {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
-    {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
-    {0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
-    {0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
-    {0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
-    {0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
-    {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
-    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}  // 00 00 00 00 00 00
-};

 void setup() {
   // initialize serial and wait for the port to open:
   Serial.begin(9600);
   while (!Serial);
-
+//    listWifiNetworks();
   // set the LED pins as outputs
   // the for() loop saves some extra coding
-  for (int pinNumber = 2; pinNumber < 5; pinNumber++) {
-    pinMode(pinNumber, OUTPUT);
-    digitalWrite(pinNumber, LOW);
-  }
-
+  for (int pinNumber = 2; pinNumber < 6; pinNumber++) {
+    if (pinNumber != 4) {
+      pinMode(pinNumber, OUTPUT);
+      digitalWrite(pinNumber, LOW);
+    }
+  }
   connectToWifi();
   connectToMQTT();
-
   setupDHT();
   SPI.begin();                // Init SPI bus
-   mfrc522.PCD_Init();         // Init MFRC522 card
-//  setupRFID();
+  mfrc522.PCD_Init();         // Init MFRC522 card
+  ShowReaderDetails();
+// client.subscribe("arduino-rfid-validation");

 }

@@ -93,68 +82,82 @@
 }

 void loop() {
-  Serial.println("DEBUG :: loop()");
-  float tempVar = readTemperature();
-  float humVar = getDHT11HumidityReadings();
-  char temp[10];
-  char humidity[10];
-  dtostrf(tempVar, 2, 2, temp);
-  dtostrf(humVar, 2, 2, humidity);
-  Serial.print("DEBUG :: Temp value return is : ");
-  Serial.println(temp);
-  Serial.print("DEBUG :: Humidity value return is : ");
-  Serial.println(humidity);
-  publishTempHumMsg(temp, humidity);
+//  Serial.println("DEBUG :: loop()");
+  if (countTempInterval == 5) {
+    countTempInterval = 0;
+    float tempVar = getTemperature();//readTemperature();
+    float humVar = getDHT11HumidityReadings();
+    char temp[10];
+    char humidity[10];
+    dtostrf(tempVar, 2, 2, temp);
+    dtostrf(humVar, 2, 2, humidity);
+    Serial.print("DEBUG :: Temp value return is : ");
+    Serial.println(temp);
+    Serial.print("DEBUG :: Humidity value return is : ");
+    Serial.println(humidity);
+    publishTempHumMsg(temp, humidity);
+  } else {
+     countTempInterval += 1;
+//     Serial.print("------------ DEBUG :: countTempInterval is : ");
+//     Serial.println(countTempInterval);
+  }
   checkTiltState();
   String rfid = getRfidUID();
   if (rfid != "") {
     Serial.print("DEBUG :: RFID value return is : ");
     Serial.println(rfid);
     publishRFIDMsg(rfid);
-  }
-  client.subscribe("arduino-rfid-validation");
-  // MQTT client loop processing
-  client.loop();
+  }
+//  else {
+//    Serial.println("DEBUG :: RFID value return is EMPTY ");
+//  }
+  //  client.subscribe("arduino-rfid-validation"
+  delay(1000);
+  //client.loop();
 }

 String getRfidUID() {
+    String rfidUid = "";
    // Look for new cards
-  if ( ! mfrc522.PICC_IsNewCardPresent()) {
+  if ( mfrc522.PICC_IsNewCardPresent()) {
      Serial.println("PICC_IsNewCardPresent loop...");
-     return "";
-  }
-
-    // Select one of the cards
-  if ( ! mfrc522.PICC_ReadCardSerial()) {
-     Serial.println("PICC_ReadCardSerial loop...");
-     return "";
-  }
-    // Show some details of the PICC (that is: the tag/card)
-
-  String rfidUid = "";
-  for (byte i = 0; i < mfrc522.uid.size; i++) {
-    rfidUid += String(mfrc522.uid.uidByte[i] < 0x10 ? "0" : "");
-    rfidUid += String(mfrc522.uid.uidByte[i], HEX);
-  }
-  Serial.print("Card UID:");
-  Serial.println(rfidUid);
-  mfrc522.PICC_HaltA();       // Halt PICC
+     if ( mfrc522.PICC_ReadCardSerial()) {
+       Serial.println("PICC_ReadCardSerial loop...");
+       for (byte i = 0; i < mfrc522.uid.size; i++) {
+        rfidUid += String(mfrc522.uid.uidByte[i] < 0x10 ? "0" : "");
+        rfidUid += String(mfrc522.uid.uidByte[i], HEX);
+      }
+      Serial.print("Card UID:");
+      Serial.println(rfidUid);
+      mfrc522.PICC_HaltA();       // Halt PICC
+    }
+  }
   return rfidUid;
 }

 void checkTiltState() {
-  tiltState = digitalRead(tiltSensorPin);
-  Serial.print("INFO :: [1 -> On, 0 -> Off] :: Tilt State is : ");
-  Serial.println(tiltState);
+  int tiltState = digitalRead(tiltSensorPin);
+//  Serial.print("INFO :: [1 -> On, 0 -> Off] :: Tilt State is : ");
+//  Serial.println(tiltState);
+  if (previousTiltState != tiltState) {
+    previousTiltState = tiltState;
     String tiltMsg = getSensorId();
     tiltMsg.concat(",");
     tiltMsg.concat(tiltState);
-//    tiltMsg.concat(",");
-//    tiltMsg.concat(time);
-    char message_buff[30];
+    char message_buff[tiltMsg.length()+1];
     tiltMsg.toCharArray(message_buff, tiltMsg.length()+1);
     //send tilt state to the tilt queue
-    client.publish("arduino-tilt-exchange", message_buff);
+    boolean result = client.publish("arduino-tilt-exchange", message_buff);
+    Serial.print("DEBUG :: arduino-tilt-exchange publish outcome : ");
+    Serial.println(result);
+    if (!result) {
+      Serial.print("ERROR :: Retry : ");
+      delay(1000);
+      result = client.publish("arduino-tilt", message_buff);
+      Serial.print("DEBUG :: arduino-tilt publish outcome 2 : ");
+      Serial.println(result);
+    }
+  }
 }

 void connectToMQTT() {
@@ -163,148 +166,75 @@
       Serial.println("INFO :: Connected to RabbitMQ");
     } else {
       Serial.println("ERROR :: Failed to Connect to RabbitMQ");
+      connectToMQTT();
     }
+//    client.subscribe("arduino-rfid-validation");
 }

 void publishRFIDMsg(String rfid) {
   //client.subscribe("inTopic");
-  Serial.println("DEBUG :: Sending RFID event : ");
-  Serial.print(rfid);
+  Serial.print("DEBUG :: Sending RFID event : ");
+  Serial.println(rfid);
   //Format for the message to the following SensorId,temperature,humidity
   String rfidMsg = getSensorId();
   rfidMsg.concat(",");
   rfidMsg.concat(rfid);
-//  tempHumMsg.concat(",");
-//  tempHumMsg.concat(humidity);
-  char message_buff[40];
+  char message_buff[rfidMsg.length()+1];
   rfidMsg.toCharArray(message_buff, rfidMsg.length()+1);
-  client.publish("arduino-rfid", message_buff);
+//  if (!client.connected()) {
+//     Serial.print("INFO :: We lost mqtt connection, reconnecting.... ");
+//     connectToMQTT();
+//  }
+  boolean result = client.publish("arduino-rfid", message_buff);
+   Serial.print("DEBUG :: arduino-rfid publish outcome : ");
+   Serial.println(result);
+   if (!result) {
+    Serial.print("ERROR :: Retry : ");
+    delay(1000);
+    result = client.publish("arduino-rfid", message_buff);
+    Serial.print("DEBUG :: arduino-rfid publish outcome 2 : ");
+    Serial.println(result);
+  }
 }

 void publishTempHumMsg(String temp, String humidity) {
-  //client.subscribe("inTopic");
-  Serial.println("DEBUG :: Sending temp ");
-  Serial.println(temp);
   //Format for the message to the following SensorId,temperature,humidity
   String tempHumMsg = getSensorId();
   tempHumMsg.concat(",");
   tempHumMsg.concat(temp);
   tempHumMsg.concat(",");
   tempHumMsg.concat(humidity);
-  char message_buff[80];
+  char message_buff[tempHumMsg.length()+1];
   tempHumMsg.toCharArray(message_buff, tempHumMsg.length()+1);
-  client.publish("arduino-weather", message_buff);
+  boolean result = client.publish("arduino-weather", message_buff);
+  Serial.print("DEBUG :: arduino-weather publish outcome : ");
+  Serial.println(result);
+  while (!result) {
+    Serial.print("ERROR :: Retry : ");
+    delay(1000);
+    result = client.publish("arduino-weather", message_buff);
+    Serial.print("DEBUG :: arduino-weather publish outcome 2 : ");
+    Serial.println(result);
+  }
 }

 String getSensorId() {
   return "need-a-sensor-id";
 }

-void printWifiData() {
-  // print your WiFi shield's IP address:
-  IPAddress ip = WiFi.localIP();
-  Serial.print("DEBUG :: IP Address: ");
-  Serial.println(ip);
-  // print MAC address:
-  byte mac[6];
-  WiFi.macAddress(mac);
-  Serial.print("DEBUG :: MAC address: ");
-  Serial.print(mac[5], HEX);
-  Serial.print(":");
-  Serial.print(mac[4], HEX);
-  Serial.print(":");
-  Serial.print(mac[3], HEX);
-  Serial.print(":");
-  Serial.print(mac[2], HEX);
-  Serial.print(":");
-  Serial.print(mac[1], HEX);
-  Serial.print(":");
-  Serial.println(mac[0], HEX);
-    // print the SSID of the network you're attached to:
-  Serial.print("DEBUG :: SSID: ");
-  Serial.println(WiFi.SSID());
-  // print the received signal strength:
-  long rssi = WiFi.RSSI();
-  Serial.print("DEBUG :: Signal strength (RSSI):");
-  Serial.println(rssi);
-  // print the encryption type:
-  byte encryption = WiFi.encryptionType();
-  Serial.print("DEBUG :: Encryption Type:");
-  Serial.println(encryption, HEX);
-}

 float getDHT11HumidityReadings() {
   float h = dht.readHumidity();
-  // Read temperature as Celsius
-  float t = dht.readTemperature();
-  // Read temperature as Fahrenheit
-  float f = dht.readTemperature(true);
-
   // Check if any reads failed and exit early (to try again).
-  if (isnan(h) || isnan(t) || isnan(f)) {
+  if (isnan(h)){// || isnan(t) || isnan(f)) {
     Serial.println("mmmmh!!! should put a retry count of 3 here !!! Failed to read from DHT sensor! looping!!");
     getDHT11HumidityReadings();
   }
-
-  // Compute heat index
-  // Must send in temp in Fahrenheit!
-  float hi = dht.computeHeatIndex(f, h);
-
-  Serial.print("Humidity: ");
-  Serial.print(h);
-  Serial.print(" %\t");
-  Serial.print("Temperature: ");
-  Serial.print(t);
-  Serial.print(" *C ");
-  Serial.print(f);
-  Serial.print(" *F\t");
-  Serial.print("Heat index: ");
-  Serial.print(hi);
-  Serial.println(" *F");
-  delay(500);
- return h;
-}
-
-float readTemperature() {
-  // read the value on AnalogIn pin 0 and store it in a variable
-  int sensorVal = analogRead(sensorPin);
-  // send the 10-bit sensor value out the serial port
-  Serial.print("DEBUG :: Sensor Value: ");
-  Serial.print(sensorVal);
-  // convert the ADC reading to voltage
-  float voltage = (sensorVal / 1024.0) * 5.0;
-  // Send the voltage level out the Serial port
-  Serial.print(", Volts: ");
-  Serial.print(voltage);
-
-  // convert the voltage to temperature in degrees C the sensor changes 10 mV per degree
-  // the datasheet says there's a 500 mV offset ((volatge - 500mV) times 100)
-  Serial.print(", degrees C: ");
-  float temperature = (voltage - .5) * 100;
-  Serial.println(temperature);
-
-  // if the current temperature is lower than the baseline turn off all LEDs
-  if (temperature < baselineTemp) { // if the temperature rises 2-4 degrees, turn an LED on
-    digitalWrite(2, LOW);
-    digitalWrite(3, LOW);
-    digitalWrite(4, LOW);
-  } else if (temperature >= baselineTemp + 2 && temperature < baselineTemp + 4) {
-    digitalWrite(2, HIGH);
-    digitalWrite(3, LOW);
-    digitalWrite(4, LOW);
-  }  else if (temperature >= baselineTemp + 4 && temperature < baselineTemp + 6) { // if the temperature rises 4-6 degrees, turn a second LED on
-    digitalWrite(2, HIGH);
-    digitalWrite(3, HIGH);
-    digitalWrite(4, LOW);
-  } else if (temperature >= baselineTemp + 6) { // if the temperature rises more than 6 degrees, turn all LEDs on
-    digitalWrite(2, HIGH);
-    digitalWrite(3, HIGH);
-    digitalWrite(4, HIGH);
-  }
-  delay(1000);
-
-  //TODO return the temperature value from this function
-  return temperature;
+  return h;
+}
+
+float getTemperature() {
+  return dht.readTemperature();
 }

 void connectToWifi() {
@@ -329,22 +259,96 @@
   }
   // you're connected now, so print out the data:
   Serial.println("DEBUG :: You're connected to the network");
-  printWifiData();
+  //printWifiData();
 }

 // handles message arrived on subscribed topic(s)
-void callback(char* topic, byte* payload, unsigned int length) {
+void callbackFunction(char* topic, byte* payload, unsigned int length) {
+  Serial.println("---------------BOOM!!!!!!!!!!!!!!!!!!--------------------- : ");
   //  arduino-rfid-validation
   String resp = String((char*)payload);
   Serial.println("Payload: " + resp);
-  Serial.print("---------------BOOM!!!!!!!!!!!!!!!!!!--------------------- : ");
+
   if (resp == "Valid") {
     digitalWrite(2, HIGH);
   } else {
     digitalWrite(3, HIGH);
   }
-  delay(1000);
+  delay(3000);
   digitalWrite(2, LOW);
   digitalWrite(3, LOW);
 }

+void ShowReaderDetails() {
+	// Get the MFRC522 software version
+	byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
+	Serial.print("MFRC522 Software Version: 0x");
+	Serial.print(v, HEX);
+	if (v == 0x91)
+		Serial.print(" = v1.0");
+	else if (v == 0x92)
+		Serial.print(" = v2.0");
+	else
+		Serial.print(" (unknown)");
+	Serial.println("");
+	// When 0x00 or 0xFF is returned, communication probably failed
+	if ((v == 0x00) || (v == 0xFF)) {
+		Serial.println("WARNING: Communication failure, is the MFRC522 properly connected?");
+	}
+}
+
+//void listWifiNetworks() {
+//  // scan for nearby networks:
+//  Serial.println("** Scan Networks **");
+//  byte numSsid = WiFi.scanNetworks();
+//
+//  // print the list of networks seen:
+//  Serial.print("number of available networks:");
+//  Serial.println(numSsid);
+//
+//  // print the network number and name for each network found:
+//  for (int thisNet = 0; thisNet<numSsid; thisNet++) {
+//    Serial.print(thisNet);
+//    Serial.print(") ");
+//    Serial.print(WiFi.SSID(thisNet));
+//    Serial.print("\tSignal: ");
+//    Serial.print(WiFi.RSSI(thisNet));
+//    Serial.print(" dBm");
+//    Serial.print("\tEncryption: ");
+//    Serial.println(WiFi.encryptionType(thisNet));
+//  }
+//}
+
+
+//void printWifiData() {
+//  // print your WiFi shield's IP address:
+//  IPAddress ip = WiFi.localIP();
+//  Serial.print("DEBUG :: IP Address: ");
+//  Serial.println(ip);
+//  // print MAC address:
+//  byte mac[6];
+//  WiFi.macAddress(mac);
+//  Serial.print("DEBUG :: MAC address: ");
+//  Serial.print(mac[5], HEX);
+//  Serial.print(":");
+//  Serial.print(mac[4], HEX);
+//  Serial.print(":");
+//  Serial.print(mac[3], HEX);
+//  Serial.print(":");
+//  Serial.print(mac[2], HEX);
+//  Serial.print(":");
+//  Serial.print(mac[1], HEX);
+//  Serial.print(":");
+//  Serial.println(mac[0], HEX);
+//    // print the SSID of the network you're attached to:
+//  Serial.print("DEBUG :: SSID: ");
+//  Serial.println(WiFi.SSID());
+//  // print the received signal strength:
+//  long rssi = WiFi.RSSI();
+//  Serial.print("DEBUG :: Signal strength (RSSI):");
+//  Serial.println(rssi);
+//  // print the encryption type:
+//  byte encryption = WiFi.encryptionType();
+//  Serial.print("DEBUG :: Encryption Type:");
+//  Serial.println(encryption, HEX);
+//}


Small tweaks.

Small tweaks.

--- laserharp.ino
+++ laserharp.ino
@@ -19,7 +19,7 @@
 //When debugging I wanted more information. So ... set this boolean to true
 //to get more stuff printed to the console. When it's true the console dumps LOTS of
 //great stuff - but the code CRAWLS and the laser harp isn't great.
-const boolean debug = true;
+const boolean debug = false;

 // Create the motor shield object with the default I2C address
 Adafruit_MotorShield AFMS = Adafruit_MotorShield();
@@ -123,7 +123,7 @@
 	if (debug) {
 		Serial.print("Height:");
 		Serial.println(height);
-	}
+	 }

 	if (height > 170) {
 		return;
@@ -261,27 +261,27 @@
 	//It's already read the zero item. So read array items 1 through 7.
 	for (int i = 1; i < numberNotes; i++) {
 		reflectedLightValues[i] = stepTheMotorAndGetLightReading(FORWARD);
-		checkSonar();
 		checkNotes(reflectedLightValues, pluckedNotes);
 	}

 	checkButtons();
+        checkSonar();

 	//It just read item 7. So going backwards, read items 6 through zero.
 	for (int i = numberNotes - 2; i >= 0; i--) {
 		reflectedLightValues[i] = stepTheMotorAndGetLightReading(BACKWARD);
-		checkSonar();
 		checkNotes(reflectedLightValues, pluckedNotes);
 	}

 	checkButtons();
-
-}
-
-
-
-
-
-
-
-
+        checkSonar();
+
+}
+
+
+
+
+
+
+
+


Commit before branching

Commit before branching

--- src/Gortobot_v3c.ino
+++ src/Gortobot_v3c.ino
@@ -45,13 +45,13 @@
 const float BATTERY_OKAY_VOLTAGE = 3.4; // system will resume program at this voltage threshold
 const int BATTERY_WAIT_TIME = 60; // seconds to wait between checking for batteryOkay
 const unsigned int FRAM_LOGGING_INTERVAL = 60; // in minutes
-const byte MESSAGE_VERSION = 2; // 2 = long form, 3 = base62
+const byte MESSAGE_VERSION = 3; // 2 = long form, 3 = base62
 const char BASE_62_CHARACTERS[63] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
 const int MINIMUM_SAIL_ANGLE = 0, MAXIMUM_SAIL_ANGLE = 360; // limits for sail
 const int TRIM_ROUTINE_MAXIMUM_SECONDS = 900; // max number of trim seconds allowed to get to ordered position. testing shows 450 should be max

 // Global variables
-unsigned long loggingInterval = 2;  // seconds b/w logging events, 1 day = 86,400 secs which is max
+unsigned long loggingInterval = 300;  // seconds b/w logging events, 1 day = 86,400 secs which is max
 unsigned int runNum;  // increments each time the device starts
 unsigned int loopCount = 0;  // increments at each loop
 boolean fixAcquired = false, staleFix = true;  // for GPS
@@ -140,6 +140,7 @@
         if (USING_WIFI) {
                 byte wifi_attempt = 1;
                 bool wifi_successful = false;
+                txSuccess = false;
                 while (wifi_attempt <= WIFI_ATTEMPT_LIMIT && !wifi_successful) {
                         if (wifi.UseWifi(logSentence)) {
                             wifi_successful = true;


BabelFish: Hide spurious zero in PROGMEM mode

--- Utils/BabelFish/BabelFish.ino
+++ Utils/BabelFish/BabelFish.ino
@@ -461,7 +461,7 @@

   byte segment[300] = {0}; // Multiple of N for padding

-  Serial.print('0'); // Signal uptream that we handle escape bytes
+  if (!gt1) Serial.print('0'); // Signal uptream that we handle escape bytes
   ask(3);
   readNext();
   word address = nextByte;


update to freeruntest but it still doesnt work right

--- arduino/motor_driver/motor_driver.ino
+++ arduino/motor_driver/motor_driver.ino
@@ -214,6 +214,8 @@
   // freerun test to exercise the motor
   else if (state==FREERUNTEST) {
     pidSetpoint = freeruncenter + freerunwidth * sin(millis() / 6000.0);
+    myPID.Compute();
+    goalSpeed = pidOutput;
   }


Got it reading and flashing data. But it looks like gemma I2C is getting corrupted data back? Tag reader has stored 11991199 Gemma is flashing 11119119 Perhaps we should slow down the SCL slightly? Logic analyser trace shows the data is coming back correctly.

--- arduino_proto/NFC_gemma/NFC_gemma.ino
+++ arduino_proto/NFC_gemma/NFC_gemma.ino
@@ -31,7 +31,8 @@
 // LED is used to put a capture region around the NDEF read, so that
 // a scope or logic analyser can easily find the frames of interest
 // by triggering on rising-high of that pin.
-#define CAPTURE LED
+#define CAPTURE  LED
+#define USER     LED

 #define NFC_ADDR_7BIT 0x56

@@ -56,14 +57,6 @@

 // The delays are required, to allow the M24SR time to process commands.

-//void loop()
-//{
-//  digitalWrite(CAPTURE, HIGH);
-//  delay(250);
-//  digitalWrite(CAPTURE, LOW);
-//  delay(250);
-//}
-
 void loop()
 {
   //Serial.println("\nstarting");
@@ -161,21 +154,27 @@
 #define PROTO_OVERHEAD 5
 // 5 bytes for NDEF header (in URI format)
 #define HEADER_LEN 5
-
-  int msgStart = 1 + HEADER_LEN;
-  int msgEnd   = 1 + HEADER_LEN + (len-HEADER_LEN);
+//2 chars for the language of a TEXT record ('en')
+#define LANGUAGE_LEN 2
+
+  // Indexes into the I2C response message of start and end of user data (for TEXT)
+  // PCB(1)+HEADER(5)+data+SW1(1)_SW2(1)+CRCH(1)+CRCL(1)
+  int msgStart = 1 + HEADER_LEN + LANGUAGE_LEN;
+  int msgEnd   = 1 + HEADER_LEN + LANGUAGE_LEN + (len-msgStart);

   Wire.requestFrom(NFC_ADDR_7BIT, len+PROTO_OVERHEAD);
   idx = 0;
+  startMsg();
   while (Wire.available())
   {
     byte b = Wire.read();
     if (idx >= msgStart && idx <= msgEnd)
     {
-  //    //Serial.write(b); //TODO process this character
+      processMsg(b);
     }
     idx++;
   }
+  endMsg();
   //Serial.println();
   //readAndDisplay(len+PROTO_OVERHEAD);

@@ -188,9 +187,11 @@
   Wire.write(deselectI2C, sizeof(deselectI2C));
   Wire.endTransmission();
   delay(1);
-  //readAndDisplay(3);
-
-  delay(1000);
+  //readAndDisplay(3);
+
+  runMsg();
+
+  delay(1000); // for debugging, separate into phases of read/process/wait
 }

@@ -237,5 +238,80 @@
   return wCrc;
 }

+
+/* This is an example of how to extract an NDEF text message.
+ * The code calls startMsg() when it thinks it is receiving a message.
+ * This is the point to clear any buffers or reset any index counters.
+ * Then it calls processMsg() for every byte received. You should
+ * process the byte then increment your indexes.
+ * Finally it calls endMsg() when finished.
+ * You should now tidy anything up such as terminate buffers.
+ * calling runMsg() should playback the sequence.
+ */
+
+/* This example stores delay lengths in a buffer. Odd indexes are the ON time in ms,
+ * event indexes are the OFF time in ms. 0 marks the end of the buffer.
+ * ASCII encoding is as follows:
+ * '0' => don't use
+ * '1' => 100ms
+ * '2' => 200ms
+ * ...
+ * '9' => 900ms
+ *
+ * You can just about flash morse code using this.
+ */
+
+#define MSG_MAX 32
+int msgIdx;
+char msg[MSG_MAX+1];
+
+void startMsg()
+{
+  msgIdx = 0;
+}
+
+void processMsg(byte b)
+{
+  char ch = (char) b;
+  if (msgIdx<MSG_MAX)
+  {
+    msg[msgIdx++] = ch;
+  }
+}
+
+void endMsg()
+{
+  msg[msgIdx] = 0; /* Make sure buffer is terminated */
+}
+
+void runMsg()
+{
+  for (int i=0; i<MSG_MAX; i++)
+  {
+    char ch = msg[i];
+    if (ch == 0)
+    {
+      break; /* early terminated message */
+    }
+    if (ch < '1' || ch > '9')
+    {
+      ch = '1';
+    }
+
+    int time =  ((int)(ch - '0')) * 100;
+    if ((i & 0x01) == 0) // odd message, turn LED on
+    {
+      digitalWrite(USER, HIGH);
+    }
+    else // even message, turn LED off
+    {
+      digitalWrite(USER, LOW);
+    }
+    delay(time);
+  }
+  // Always leave LED off at end
+  digitalWrite(USER, LOW);
+}
+
 /* END OF FILE */


Change pin numbers for A-Star 32U4

Change pin numbers for A-Star 32U4

Signed-off-by: Mark Knoop <f1b5a91d4d6ad523f2610114591c007e75d15084@markknoop.com>

--- src/sketch.ino
+++ src/sketch.ino
@@ -3,9 +3,11 @@
  */

 // motor pins
-#define stepPin        11
-#define dirPin         12
-#define sensorPin      13
+#define stepPin         9
+#define dirPin          7
+#define enablePin       5
+#define alarmPin        3
+#define sensorPin      11

 // speeds
 #define pulseWidth      5
@@ -70,16 +72,26 @@
 void setup() {
     pinMode(stepPin, OUTPUT);
     pinMode(dirPin, OUTPUT);
+    pinMode(enablePin, OUTPUT);
+    pinMode(alarmPin, INPUT_PULLUP);
     pinMode(sensorPin, INPUT_PULLUP);
     pinMode(A0, INPUT_PULLUP);
     pinMode(A1, INPUT_PULLUP);
     pinMode(A2, INPUT_PULLUP);
     pinMode(A3, INPUT_PULLUP);
     digitalWrite(dirPin, HIGH);
+    digitalWrite(enablePin, LOW);
     Serial.begin(38400);
+    blink();
     findsensor(maxPulse);
     defaults();
-    sendid();
+    //sendid();
+}
+
+void blink() {
+    digitalWrite(13, HIGH);
+    delay(50);
+    digitalWrite(13, LOW);
 }

 void defaults() {
@@ -553,9 +565,11 @@
 }

 void loop() {
+    /* DEBUG gliss code
     receivedata();
     if (newData) processdata();
-    /* DEBUG gliss code
+    */
+    blink();
     durationturn(2000, 60, true, false);
     delay(1000);
     durationturn(2000, 67, true, false);
@@ -563,6 +577,7 @@
     durationturn(2000, 72, true, false);
     delay(1000);
     durationturn(1500, 60, true, false);
+    blink();
     delay(500);
     durationgliss(1500, 60, 72, true, false, 0);
     delay(1500);
@@ -570,11 +585,11 @@
     delay(500);
     durationgliss(6000, 55, 72, true, false, 900);
     delay(500);
+    blink();
     doublegliss(6000, 6000, 55, 67, 60, 500, 500, 500, true, false);
     delay(500);
     doublegliss(707, 707, 60, 72, 71, 50, 50, 50, true, false);
-    //delay(1500);
+    delay(1500);
     //_durationgliss(1500, 60, 60, true, false, true, true, 50, 50);
     //delay(2000);
-    */
-}
+}


cleanup code.

cleanup code.

--- modbusserialtest/modbusserialtest.ino
+++ modbusserialtest/modbusserialtest.ino
@@ -30,25 +30,14 @@
     mb.addDimp(DISCINP);
     mb.addIreg(INPREG);

-    mb.Hreg(TESTREG, 222);
+    mb.Hreg(TESTREG, 314);
     mb.Dimp(DISCINP, true);
-    mb.Ireg(INPREG, 38);
+    mb.Ireg(INPREG, 0);
+    mb.Coil(COIL1, false);
+    mb.Coil(COIL2, false);

     t1 = millis();
     t2 = millis();
-
-    mb.Coil(COIL1, false);
-    mb.Coil(COIL2, false);
-
-    digitalWrite(ledPin, false);
-    delay(1000);
-    digitalWrite(ledPin, true);
-    delay(100);
-    digitalWrite(ledPin, false);
-    delay(1000);
-    digitalWrite(ledPin, true);
-    delay(100);
-    digitalWrite(ledPin, false);
 }

 void loop() {


Adjusting panic() with message for clarity.

--- V0p2_Main/V0p2_Main.ino
+++ V0p2_Main/V0p2_Main.ino
@@ -92,6 +92,8 @@
 // Panic with fixed message.
 void panic(const __FlashStringHelper *s)
   {
+  OTV0P2BASE::serialPrintlnAndFlush(); // Start new line to highlight error.  // May fail.
+  OTV0P2BASE::serialPrintAndFlush('!'); // Indicate error with leading '!' // May fail.
   OTV0P2BASE::serialPrintlnAndFlush(s); // May fail.
   panic();
   }


Write log to SD card; delete Serial.prints to make space.

--- RouterReset.ino
+++ RouterReset.ino
@@ -12,10 +12,9 @@
 #include <stdio.h>
 #include <SPI.h>
 #include <WiFi.h>
-#include <SPI.h>
 #include <WiFiUdp.h>
 #include <Time.h>
-
+#include <SD.h>

 // private info [made generic here]
 char ssid[] = "SSID";
@@ -31,9 +30,9 @@

 // checking connection
 unsigned long lastConnectionTime = 0;
-boolean lastConnected = false;
 const unsigned long postingInterval = 10*1000; // wait 10 seconds
 boolean canConnect = false;
+boolean canConnect_prev = false;

 // setting time
 unsigned int localPort = 2390;      // local port to listen for UDP packets
@@ -45,9 +44,14 @@
 WiFiUDP Udp;
 char time_as_string[] = "12/20/1969 00:00:00";

+// LED pins
 const int redLed = 3;
 const int greenLed = 5;
 const int yellowLed = 6;
+
+// SD card
+const int chipSelect = 4;
+File logfile;

 void setup() {
   // Initial LEDs
@@ -56,49 +60,35 @@
   pinMode(yellowLed, OUTPUT);

   //Initialize serial and wait for port to open:
-  Serial.begin(9600);
   flash_3leds(redLed, greenLed, yellowLed, 5, 100);
-  while (!Serial) { ; } // wait for serial port to connect.
   flash_3leds(redLed, greenLed, yellowLed, 5, 400);

   // check for the presence of the shield:
   if (WiFi.status() == WL_NO_SHIELD) {
-    Serial.println("WiFi shield not present");
     while (true); // stop
   }

   String fv = WiFi.firmwareVersion();
-  if ( fv != "1.1.0" )
-    Serial.println("Please upgrade the firmware");
-  Serial.print("Wifi firmware: ");
-  Serial.println(fv);

   // attempt to connect to Wifi network:
   while (status != WL_CONNECTED) {
-    Serial.print("Attempting to connect to SSID: ");
-    Serial.println(ssid);
     status = WiFi.begin(ssid, pass);

     delay(1000);
   }
-  Serial.println("Connected to wifi");
-  printWifiStatus();
-
-  Serial.println("Connecting to time server.");
   Udp.begin(localPort);

-  Serial.println("Getting time.");
   sendNTPpacket(timeServer); // send an NTP packet to a time server
   delay(500);
-  if(  Udp.parsePacket() ) get_and_print_time();
+  if( Udp.parsePacket() ) get_and_set_time();
+
+  open_file();
 }

 void loop() {
   // if there are incoming bytes available
   // from the server, read them and print them:
   while (client.available()) {
-    Serial.println("Client avaliable.");
-    Serial.println("Disconnecting...");
     lastConnectionTime=millis();
     client.stop();
   }
@@ -108,12 +98,8 @@
     connect_to_server();
     digitalWrite(yellowLed, LOW);

-    Serial.print("Current time: ");
-    time_to_string(now(), time_as_string);
-    Serial.println(time_as_string);
   }

-  lastConnected = client.connected();
   if(canConnect) {
     digitalWrite(greenLed, HIGH);
     digitalWrite(redLed, LOW);
@@ -122,33 +108,21 @@
     digitalWrite(greenLed, LOW);
     digitalWrite(redLed, HIGH);
   }
+  if(canConnect != canConnect_prev) {
+    time_to_string(now(), time_as_string);
+    logfile.print(time_as_string);
+    logfile.print(" - ");
+    if(canConnect) logfile.println("connected.");
+    else logfile.println("NOT CONNECTED!");
+    logfile.flush();

-}
-
-void printWifiStatus() {
-  // print the SSID of the network you're attached to:
-  Serial.print("SSID: ");
-  Serial.println(WiFi.SSID());
-
-  // print your WiFi shield's IP address:
-  IPAddress ip = WiFi.localIP();
-  Serial.print("IP Address: ");
-  Serial.println(ip);
-
-  // print the received signal strength:
-  long rssi = WiFi.RSSI();
-  Serial.print("signal strength (RSSI):");
-  Serial.print(rssi);
-  Serial.println(" dBm");
+    canConnect_prev = canConnect;
+  }
 }

 void connect_to_server(void) {
-  Serial.println("\nStarting connection to server...");
-  // if you get a connection, report back via serial:
   if (client.connect(server, 80)) {
     canConnect = true;
-    Serial.println("connected to server");
-    // Make a HTTP request:
     client.println("GET /search?q=arduino HTTP/1.1");
     client.println("Host: www.google.com");
     client.println("Connection: close");
@@ -156,7 +130,6 @@
   }
   else {
     client.stop();
-    Serial.println("CONNECTION PROBLEM");
     canConnect = false;
   }
   lastConnectionTime=millis();
@@ -195,30 +168,30 @@
   Udp.endPacket();
 }

-void get_and_print_time(void) {
-    Serial.println("packet received");
+void get_and_set_time(void) {
     Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer

     unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
     unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
     unsigned long secsSince1900 = highWord << 16 | lowWord;

-    // now convert NTP time into everyday time:
     const unsigned long seventyYears = 2208988800UL;
-    // subtract seventy years:
     unsigned long epoch = secsSince1900 - seventyYears;
     setTime(epoch);
-
-    Serial.print("Current time: ");
-    time_to_string(epoch, time_as_string);
-    Serial.println(time_as_string);
 }

 void time_to_string(unsigned long epoch, char* time_as_string) {
-
-  epoch = epoch + TIMEZONE * 3600;
-
-  sprintf(time_as_string, "%02d/%02d/%4d %d:%02d:%02d",
+    epoch = now() + TIMEZONE * 3600;
+    sprintf(time_as_string, "%02d/%02d/%4d %d:%02d:%02d",
           month(epoch), day(epoch), year(epoch),
           hour(epoch), minute(epoch), second(epoch));
 }
+
+void open_file(void) {
+  char filename[] = "log_****-11-11_12:59:59.csv";
+
+  sprintf(filename, "log_%4d-%02d-%02d_%02d:%02d:%02d.csv",
+          year(), month(), day(), hour(), minute(), second());
+
+  logfile = SD.open(filename, FILE_WRITE);
+}


RobotFirmware: added register structure according to documentation

--- platform_src/RobotFirmware/RobotFirmware.ino
+++ platform_src/RobotFirmware/RobotFirmware.ino
@@ -1,9 +1,52 @@
+#include <SimpleModbusSlave.h>
+#include <ArduinoRobot.h>
+#include <Wire.h>
+#include <SPI.h>
+#include <math.h>
+
+enum
+{
+  // just add or remove registers and your good to go...
+  // The first register starts at address 0
+  IR,
+  VOLTS,
+  FLOOR,
+  E3,
+  E4,
+  E5,
+  E6,
+  E7,
+  E8,
+  E9,
+  EA,
+  EB,
+  EC,
+  ED,
+  EE,
+  EF,
+  LWS,//left wheel speed
+  RWD,//right wheel speed
+  E12,
+  E13,
+  E14,
+  E15,
+  MVCMD,//move command, see protocol description, write only
+  E17,
+  E18,
+  E19,
+  E20,
+  TOTAL_ERRORS,
+  // leave this one
+  TOTAL_REGS_SIZE
+  // total number of registers for function 3 and 16 share the same register array
+};
+
+unsigned int holdingRegs[TOTAL_REGS_SIZE];
 void setup() {
-  // put your setup code here, to run once:
-
+  Robot.begin();
+  modbus_configure(115200, 1, 0, TOTAL_REGS_SIZE, 0);
 }

 void loop() {
-  // put your main code here, to run repeatedly:
-
+  holdingRegs[TOTAL_ERRORS] = modbus_update(holdingRegs);
 }


Tweaks

Tweaks

--- Pan_Tilt_laser/Pan_Tilt_laser.ino
+++ Pan_Tilt_laser/Pan_Tilt_laser.ino
@@ -38,7 +38,7 @@
 //Y Position: lower numbers == Up

 panTiltPos_t panTiltX(0, 55, 125, -20);
-panTiltPos_t panTiltY(0, 10, 45, 0, 5);
+panTiltPos_t panTiltY(0, 10, 45, 0, 10);

 PanTilt panTilt(9, &panTiltX, 10, &panTiltY, 98);
@@ -167,10 +167,10 @@
   }

   else if(oldSpeed == midVal){
-    if(probability < 40){
+    if(probability < 30){
       return hiVal;
     }
-    else if(probability < 90){
+    else if(probability < 80){
       return midVal;
     }
     else{
@@ -179,7 +179,7 @@
   }

   else if(oldSpeed == hiVal){
-    if(probability < 50){
+    if(probability < 60){
       return midVal;
     }
     else{


Fix typo

Fix typo

--- GarHAge.ino
+++ GarHAge.ino
@@ -126,7 +126,7 @@
       client.publish(mqtt_door1_status_topic, "open", true);
     }
     else if (digitalRead(door1_statusPin) == LOW) {
-      Serial.print(door2_alias);
+      Serial.print(door1_alias);
       Serial.print(" closed! Publishing to ");
       Serial.print(mqtt_door1_status_topic);
       Serial.println("...");


Adding MID used libraries

Adding MID used libraries

--- MID/MID.ino
+++ MID/MID.ino
@@ -98,23 +98,24 @@
 #include <LiquidCrystal.h>
 //
 // Interval / Amplitude
-#include "lib/IntAmp.h"
+#include "./lib/IntAmp.h"
 //
 // Adding Alphine emulator
-#include "lib/WhlSens.h"
+#include "./lib/WhlSens.h"
 //
 // Main Sensor handler
-#include "lib/MainFunc.h"
-
+#include "./lib/MainFunc.h"
 //
 // Engine sensors
-#include "lib/CarSens.h"
+#include "./lib/CarSens.h"
+
 //
 // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7)
 LiquidCrystal lcd(32, 33, 34, 35, 36, 37);
 //
 // Special characters
-#include "lib/LcdChar.h"
+#include "./lib/LcdChar.h"
+
 //
 // Menu cursor
 int cursorMenu = 0;


Calibrates the magnetometer.

Calibrates the magnetometer.

--- tanduino/tanduino.ino
+++ tanduino/tanduino.ino
@@ -32,7 +32,6 @@
  * TODOs:
  *  - calibration: http://www.nxp.com/files/sensors/doc/app_note/AN4246.pdf
  *  - add calibration method to the documentation
- *  - create a calibration sketch
  *  - add a picture of the prototype to the documentation
  */

@@ -117,11 +116,11 @@
 static const V
   _orientationADXL345 =               {-1, 1, 1},     // {x, y, z} Configuration vector to align the sensor output with the device coordinate system (NED: North, East, Down). Modify it as needed.
   _orientationHMC5883 =               {1, -1, -1},    // {x, y, z} Configuration vector to align the sensor output with the device coordinate system (NED: North, East, Down). Modify it as needed.
-  _biasHMC5883 =                      {0, 0, 0};      // {x, y, z} Calibration vector used to correct the Hard Iron effect. Modify it as needed.
+  _biasHMC5883 =                      {18.95, 7.244, 5.401};  // {x, y, z} Calibration vector used to correct the Hard Iron effect. Modify it as needed.
 static const M
-  _matrixHMC5883 =                    {1, 0, 0,       // Calibration matrix used to correct the Soft Iron effect. Modify it as needed.
-                                       0, 1, 0,
-                                       0, 0, 1};
+  _matrixHMC5883 =                    {1.442, -0.062, -0.053, // Calibration matrix used to correct the Soft Iron effect. Modify it as needed.
+                                       -0.032, 1.497, 0.055,
+                                       -0.117, 0.052, 1.554};

 // Global variables
 Adafruit_PCD8544 _PCD8544 =           Adafruit_PCD8544(PCD8544_DC_PIN, PCD8544_CE_PIN, PCD8544_RST_PIN);


Update SBR.ino

Update SBR.ino

--- SBR/SBR.ino
+++ SBR/SBR.ino
@@ -22,6 +22,7 @@
 int depth = A0;
 int x=0;
 float starttime;
+float begintime;
 float tank;
 float airtimer;
 void setup() {
@@ -65,11 +66,24 @@
   measurevol();
 }
 uint8_t i=0;
+void measurevol(){
+  int junk = analogRead(depth);
+  float tank1 = analogRead(depth)*0.421569-28.4559;
+  float tank2 = analogRead(depth)*0.421569-28.4559;//*0.438596-32.7018;
+  float tank3 = analogRead(depth)*0.421569-28.4559;//*0.438596-32.7018;
+  float tank4 = analogRead(depth)*0.421569-28.4559;//*0.438596-32.7018;
+  float tank5 = analogRead(depth)*0.421569-28.4559;//*0.438596-32.7018;
+  float tank6 = analogRead(depth)*0.421569-28.4559;//*0.438596-32.7018;
+  float tank7 = analogRead(depth)*0.421569-28.4559;//*0.438596-32.7018;
+  float tank8 = analogRead(depth)*0.421569-28.4559;//*0.438596-32.7018;
+  tank = (tank1 + tank2 + tank3 + tank4 + tank5 + tank6 + tank7 + tank8)/8;
+}

 void loop() {
   // put your main code here, to run repeatedly:
   DateTime now = rtc.now();
+  float current = now.unixtime();
   lcd.setCursor(0, 0);
   lcd.print(now.unixtime());
   lcd.setCursor(0, 1);
@@ -88,47 +102,10 @@
   lcd.print(tank);
   //write conditions for running sequence here and add functions
   while (x<1){
-    normalsequence();
+   loading();
     x++;}
   }
-void weekend(){
-  aeration(15, 4);
-  rest(45);
-}
-void normalsequence(){
-  DateTime now = rtc.now();
-  starttime = now.unixtime();
-  //fill(10);
-  now = rtc.now();
-  starttime = now.unixtime();
-  //fill(13);
-  now = rtc.now();
-  starttime = now.unixtime();
-  fill(16);
-  now = rtc.now();
-  starttime = now.unixtime();
-  fill(19);
-  now = rtc.now();
-  starttime = now.unixtime();
-  fill(22);
-  now = rtc.now();
-  starttime = now.unixtime();
-  fill(25);
-  now = rtc.now();
-  delay(5000);
-  aeration(240, 24);
-  delay(5000);
-  settle(60, 24);
-  delay(5000);
-  skim(60);
-  delay(5000);
-  settle(120,24);
-  delay(5000);
-  decant(6);
-  delay(5000);
-  //rest(5);
-  delay(5000);
-}
+
 void fill(int lvl){//check depth and fill until level is 25gal plus stir
   digitalWrite(stir, HIGH);
   lcd.clear();
@@ -139,9 +116,6 @@
   lcd.setCursor(0,1);
   lcd.print(tank);lcd.print("gal");
   DateTime now = rtc.now();
-   while (now.unixtime()-starttime <3600000){
-
-    DateTime now = rtc.now();
     while (tank<lvl){
       digitalWrite(fillpump, HIGH);
       measurevol();
@@ -150,30 +124,31 @@
       delay(15000);
     }
     digitalWrite(fillpump, LOW);
-    periodicaeration(15,60, now.unixtime());
-    delay(15000);
-}}
-
-void periodicaeration(float ontime, float onfreq, float tt){//on for 15 min freq is 60 min
-  ontime=ontime*60*1000;
-  onfreq=onfreq*60*1000;
-  if (onfreq-ontime>tt-starttime){
-  lcd.clear();
-  lcd.setCursor(0,0);
-  lcd.print("Periodic Aeration ");
+}
+
+void periodicaeration(float ontime){//on for 15 min freq is 60 min
+  ontime=ontime*60;
+  lcd.clear();
+  lcd.setCursor(0,0);
+  lcd.print("PeriodicAeration ");
   DateTime now = rtc.now();
-  float current = now.unixtime();
-  while (current-tt < ontime){
-    float timedisplay= (ontime-(current-tt))*1000*60;
+  float tt = now.unixtime();
+  float current=tt;
+  int timedisplay = round((ontime-(current-tt))/60);
+  while ((current-tt) < ontime){
+    timedisplay = round((ontime-(current-tt))/60);
+    measurevol();
     lcd.setCursor(0,1);
+  lcd.print(tank);lcd.print("gal  ");
   lcd.print(timedisplay);
+  lcd.print("min");
   delay(1000);
   digitalWrite(air, HIGH);
-  DateTime now = rtc.now();
+  now = rtc.now();
   current = now.unixtime();
   }
-digitalWrite(air, LOW);  }
-  }
+digitalWrite(air, LOW);
+}
 void aeration(float airduration, int lvl){//duration in min check depth and keep air on and pumps off for time period
   airduration=airduration*60*1000;
   lcd.clear();
@@ -276,16 +251,60 @@
   digitalWrite(en1, HIGH);
 }
 }
-
-void measurevol(){
-  int junk = analogRead(depth);
-  float tank1 = analogRead(depth)*0.421569-28.4559;
-  float tank2 = analogRead(depth)*0.421569-28.4559;//*0.438596-32.7018;
-  float tank3 = analogRead(depth)*0.421569-28.4559;//*0.438596-32.7018;
-  float tank4 = analogRead(depth)*0.421569-28.4559;//*0.438596-32.7018;
-  float tank5 = analogRead(depth)*0.421569-28.4559;//*0.438596-32.7018;
-  float tank6 = analogRead(depth)*0.421569-28.4559;//*0.438596-32.7018;
-  float tank7 = analogRead(depth)*0.421569-28.4559;//*0.438596-32.7018;
-  float tank8 = analogRead(depth)*0.421569-28.4559;//*0.438596-32.7018;
-  tank = (tank1 + tank2 + tank3 + tank4 + tank5 + tank6 + tank7 + tank8)/8;
-}
+void weekend(){
+  aeration(15, 4);
+  rest(45);
+}
+void normalsequence(){
+  DateTime now = rtc.now();
+  starttime = now.unixtime();
+  //fill(10);
+  now = rtc.now();
+  starttime = now.unixtime();
+  //fill(13);
+  now = rtc.now();
+  starttime = now.unixtime();
+  fill(16);
+  now = rtc.now();
+  starttime = now.unixtime();
+  fill(19);
+  now = rtc.now();
+  starttime = now.unixtime();
+  fill(22);
+  now = rtc.now();
+  starttime = now.unixtime();
+  fill(25);
+  now = rtc.now();
+  delay(5000);
+  aeration(240, 24);
+  delay(5000);
+  settle(60, 24);
+  delay(5000);
+  skim(60);
+  delay(5000);
+  settle(120,24);
+  delay(5000);
+  decant(6);
+  delay(5000);
+  //rest(5);
+  delay(5000);
+}
+void loading(){
+   DateTime now = rtc.now();
+  begintime = now.unixtime();
+   measurevol();
+   fill(18);
+   periodicaeration(15);
+   now = rtc.now();
+  float current = now.unixtime();
+  while (current-begintime<3600000){//1hr
+    now = rtc.now();
+    current = now.unixtime();
+    delay(15000);
+    lcd.setCursor(0,0);
+  lcd.print("Loading");
+
+  }
+
+  fill(19);
+}


Restored temperature logging for data collection. Changed switch:(0|1) to relay:(on|off). Fixed setup() comment (it is a cooler, not a heater)

--- controller/controller.ino
+++ controller/controller.ino
@@ -101,6 +101,7 @@
 void readTemperature() {
     sensors.requestTemperatures();
     temperature = (double)sensors.getTempFByIndex(0);
+    logData("temp", temperature);
 }

 /**
@@ -112,14 +113,14 @@
         if (relay_status != LOW) {
             relay_status = LOW;
             digitalWrite(PIN_RELAY, relay_status);
-            logData("switch", 1);
+            logData("relay", "on");
         }
     } else {
         if (temperature < targetTemp-TEMP_OFFSET) {
             if (relay_status != HIGH) {
                 relay_status = HIGH;
                 digitalWrite(PIN_RELAY, relay_status);
-                logData("switch", 0);
+                logData("relay", "off");
             }
         }
     }
@@ -130,7 +131,7 @@
     // setup temperature sensors
     sensors.begin();
     targetTemp = TEMP_TARGET;
-    // setup heater relay
+    // setup cooler relay
     pinMode(PIN_RELAY, OUTPUT);
     digitalWrite(PIN_RELAY, relay_status);
 }


Negative temp handling, parameterize interval

--- controller/controller.ino
+++ controller/controller.ino
@@ -41,8 +41,9 @@

 float tank_max_temp = 140;      // Deg. F; above this, pump is off
 float collector_min_temp = 40;  // Deg. F; below this, pump is off
-float on_threshold = 10;         // Deg. F differential before pump turns on
-float off_threshold = 10;        // Deg. F differential before pump turns off
+float on_threshold = 10;        // Deg. F differential before pump turns on
+float off_threshold = 10;       // Deg. F differential before pump turns off
+int interval = 60000;           // Delay in ms between readings

 /*
  * setup() - this function runs once when you turn your Arduino on
@@ -80,10 +81,13 @@
   float tank_temp = sensors.getTempF(tank_sensor);
   float collector_temp = sensors.getTempF(collector_sensor);

-  if (tank_temp < 0 || collector_temp < 0) {
+  print_temps(tank_temp, collector_temp);
+
+  // Assume that very negative readings are errors
+  if (tank_temp < -50 || collector_temp < -50) {
     Serial.println("Screwy reading, ignoring");
   }
-
+
   // If tank is hot enough, pump is off
   else if (tank_temp >= tank_max_temp) {
     Serial.println("Tank is over max temp, pump off");
@@ -112,8 +116,6 @@
   else {
   }

-  print_temps(tank_temp, collector_temp);
-
-  delay(60000);
+  delay(interval);
 }


Pins changed on real hardware

Pins changed on real hardware

--- LightSwitch.ino
+++ LightSwitch.ino
@@ -1,7 +1,7 @@
-#define LIGHT1 8
-#define LIGHT2 9
-#define BTN1 4
-#define BTN2 5
+#define LIGHT1 7
+#define LIGHT2 6
+#define BTN1 9
+#define BTN2 8
 #define TICKER 6000
 #define DELAY 10


Update Cock_HEX.ino

Update Cock_HEX.ino

--- IHM595/exemples/Cock_HEX/Cock_HEX.ino
+++ IHM595/exemples/Cock_HEX/Cock_HEX.ino
@@ -15,7 +15,6 @@
 IHM595 board(2,3,4);

 void setup() {
-  board.begin();
   board.background(HIGH);
   board.set(5,0);
   String a = "UPTime";