Menu and Gauge mode was added

Menu and Gauge mode was added

--- DiveIno.ino
+++ DiveIno.ino
@@ -1,4 +1,4 @@
-#include "SparkFun_MS5803_I2C.h"
+#include "MS5803_I2C.h"
 #include "SPI.h"
 #include "Wire.h"
 #include "DiveDeco.h"
@@ -44,7 +44,7 @@
 const char* METER = "meter";
 const char* CEL_SHORT = "cel";

-char* mainMenu[] = {" DiveIno ",
+char* mainMenu[] = {" DiveIno - Main Menu ",
                 " Dive",
                 " Logbook",
 				" Surface Time",
@@ -54,7 +54,7 @@
 #define MENU_SIZE (sizeof(mainMenu)/sizeof(char *))-1

 // Position of first menu item from the top of the screen
-#define MENU_TOP 20
+#define MENU_TOP 30
 // Currently elected menu item
 byte selectedMenuItemIndex;

@@ -137,30 +137,28 @@
 	// Button Handling //
 	/////////////////////

-
+	if (irrecv.decode(&results)) {
+		processRemoteButtonPress(&results);
+		irrecv.resume(); // Receive the next value
+	}

 	/////////////////////
 	// Sensor handling //
 	/////////////////////

 	switch (currentScreen) {
-		case DIVE_START_SCREEN: {
-			// Read pressure from the sensor in mbar.
+		case GAUGE_SCREEN: {
 			float pressureInMillibar = sensor.getPressure(ADC_4096);
-
-			//Switch to DIVE PROGRESS mode, if the diver has already descended below 2 meters
-			if (pressureInMillibar > 1200) {
-				diveStartButtonPressed();
+			if (pressureInMillibar > seaLevelAtmosphericPressure) {
+				depthInMeter = diveDeco.calculateDepthFromPressure(pressureInMillibar);
 			} else {
-				if (pressureInMillibar > seaLevelAtmosphericPressure) {
-					depthInMeter = diveDeco.calculateDepthFromPressure(pressureInMillibar);
-				}
-				float temperatureInCelsius = sensor.getTemperature(CELSIUS, ADC_512);
-
-				drawCurrentTemperature(temperatureInCelsius);
-				drawCurrentPressure(pressureInMillibar);
-				drawDepth(depthInMeter);
-			}
+				depthInMeter = 0;
+			}
+			float temperatureInCelsius = sensor.getTemperature(CELSIUS, ADC_512);
+
+			drawCurrentPressure(pressureInMillibar);
+			drawDepth(depthInMeter);
+			drawCurrentTemperature(temperatureInCelsius);
 		}
 		break;
 		case DIVE_SCREEN: {
@@ -275,35 +273,88 @@

 		//Switch to DIVE_STOP mode
 		currentMode = DIVE_STOP_MODE;
-		displayScreen(DIVE_STOP_SCREEN);
+		//displayScreen(DIVE_STOP_SCREEN);

 		//TODO Start surface time counter
 	}
 }

+////////////////////////////////////////////////////////////////////
+
+void processRemoteButtonPress(decode_results *results) {
+	if (results->value == 0xFD8877 || results->value == 0xFF629D) {
+		if (testMode) {
+			Serial.println("Up");
+			tone(speakerPin, 261, 10);
+		}
+		upButtonPressed();
+	} else if (results->value == 0xFD9867 || results->value == 0xFFA857) {
+		if (testMode) {
+			Serial.println("Down");
+			tone(speakerPin, 261, 10);
+		}
+		downButtonPressed();
+	} else if (results->value == 0xFDA857 || results->value == 0xFF02FD) {
+		if (testMode) {
+			Serial.println("OK");
+			tone(speakerPin, 261, 10);
+		}
+		selectButtonPressed();
+	}
+}
+
+// This is the OK or the Prev button on the IR Remote Control
 void selectButtonPressed() {
-	if (currentMode == SURFACE_MODE) {
+	if (currentScreen == MENU_SCREEN) {
 		switch (selectedMenuItemIndex) {
-			case 1: {
+			case 1: { //Dive
 				currentMode = DIVE_START_MODE;
-				displayScreen(DIVE_START_SCREEN);
+				displayScreen(DIVE_SCREEN);
 			}
 			break;
-			case 2 : { //Last dive
-				currentMode = DIVE_STOP_MODE;
-				displayScreen(DIVE_STOP_SCREEN);
+			case 2: { //Logbook
+				currentMode = SURFACE_MODE;
+				displayScreen(LOGBOOK_SCREEN);
 			}
 			break;
-		}
-	} else if (currentMode == DIVE_STOP_MODE || currentMode == DIVE_START_MODE) {
-		//Go back to the main menu
+			case 3: { //Surface time
+				currentMode = SURFACE_MODE;
+				displayScreen(SURFACE_TIME_SCREEN);
+			}
+			break;
+			case 4: { //Gauge
+				currentMode = GAUGE_MODE;
+				displayScreen(GAUGE_SCREEN);
+			}
+			break;
+			case 5: { //Settings
+				currentMode = SURFACE_MODE;
+				displayScreen(SETTINGS_SCREEN);
+			}
+			break;
+		}
+	} else if (currentScreen == GAUGE_SCREEN) {
 		currentMode = SURFACE_MODE;
 		displayScreen(MENU_SCREEN);
 	}
 }

-void navigationButtonPressed() {
-	if (currentMode == SURFACE_MODE) {
+// This is the Up or the Mode button on the IR Remote Control
+void upButtonPressed() {
+	if (currentScreen == MENU_SCREEN) {
+		if (selectedMenuItemIndex == 1) {
+			// Position to the last menu item
+			menuSelect(MENU_SIZE);
+		} else {
+			// Move down the selection
+			menuSelect(selectedMenuItemIndex - 1);
+		}
+	}
+}
+
+// This is the Down or the - button on the IR Remote Control
+void downButtonPressed() {
+	if (currentScreen == MENU_SCREEN) {
 		if (selectedMenuItemIndex < MENU_SIZE) {
 			// Move down the selection
 			menuSelect(selectedMenuItemIndex + 1);
@@ -317,7 +368,7 @@
 void diveStartButtonPressed() {
 	if (currentMode == SURFACE_MODE) {
 		currentMode = DIVE_START_MODE;
-		displayScreen(DIVE_START_SCREEN);
+		//displayScreen(DIVE_START_SCREEN);
 	} else if (currentMode == DIVE_START_MODE) {
 		//Start to count the duration of the dive
 		diveDurationInSeconds = 0;
@@ -343,11 +394,28 @@
 	}
 }

+///////////////////////////////////////////////////////////////
+
+void menuSelect(byte menuItemIndex) {
+
+	tft.setColor(VGA_YELLOW);
+
+	// Remove the highlight from the currently selected menu item
+	tft.setBackColor(VGA_BLACK);
+	tft.print(mainMenu[selectedMenuItemIndex], 0, ((selectedMenuItemIndex - 1) * 16) + MENU_TOP);
+
+	// Highlight the new selected menu item
+	tft.setBackColor(VGA_BLUE);
+	tft.print(mainMenu[menuItemIndex], 0, ((menuItemIndex - 1) * 16) + MENU_TOP);
+
+	// Save the selection
+	selectedMenuItemIndex = menuItemIndex;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
 void displayScreen(byte screen) {
 	currentScreen = screen;
-
-	//Clear the screen
-	tft.clrScr();

 	switch (screen) {
 		case MENU_SCREEN:
@@ -357,18 +425,8 @@
 			selectedMenuItemIndex = 1;
 			menuSelect(selectedMenuItemIndex);
 			break;
-		case DIVE_SCREEN:
-			displayDiveScreen();
-
-			drawDepth(0);
-			drawMaximumDepth(0);
-			drawDiveDuration(0);
-			drawCurrentTemperature(0);
-			drawCurrentPressure(0);
-			drawOxigenPercentage(21);
-			break;
-		case DIVE_STOP_SCREEN:
-			displayDiveStopScreen();
+		case GAUGE_SCREEN:
+			displayGaugeScreen();
 			break;
 	}
 }
@@ -377,13 +435,14 @@

 	// Clear the screen
 	tft.clrScr();
+	tft.setFont(BigFont);

 	// Display the header of the menu - the header is the first item
 	tft.setColor(VGA_LIME);
-	tft.print(mainMenu[0], 0, 0);
+	tft.print(mainMenu[0], 48, 0);

 	// Draw separation line
-	tft.drawLine(0, 0, tft.getDisplayXSize(), 0);
+	tft.drawLine(0, MENU_TOP-5, tft.getDisplayXSize()-1, MENU_TOP-5);

 	// Display other menu items
 	tft.setColor(VGA_YELLOW);
@@ -392,32 +451,38 @@
 	}
 }

-void menuSelect(byte menuItemIndex) {
+void displayGaugeScreen() {
+
+	// Clear the screen
+	tft.clrScr();
+	tft.setFont(BigFont);
+
+	// Display the header of the menu - the header is the first item
+	tft.setColor(VGA_LIME);
+	tft.setBackColor(VGA_BLACK);
+	tft.print("Gauge", 128, 6);

 	tft.setColor(VGA_YELLOW);
-
-	// Remove the highlight from the currently selected menu item
-	tft.setBackColor(VGA_BLACK);
-	tft.print(mainMenu[selectedMenuItemIndex], 0, ((selectedMenuItemIndex - 1) * 16) + MENU_TOP);
-
-	// Highlight the new selected menu item
-	tft.setBackColor(VGA_BLUE);
-	tft.print(mainMenu[menuItemIndex], 0, ((menuItemIndex - 1) * 16) + MENU_TOP);
-
-	// Save the selection
-	selectedMenuItemIndex = menuItemIndex;
-}
-
-void displayDiveScreen() {
-	//TODO
-}
-
-void displayDiveStopScreen() {
-	//TODO
+	tft.print("Depth", 16, 32);
+	tft.print("Temperature", 16, 102);
+	tft.print("Pressure", 16, 172);
+	tft.print("Time", 16, 242);
+
+	tft.setColor(VGA_SILVER);
+	tft.drawRect(0, 0, tft.getDisplayXSize()-1, tft.getDisplayYSize()-1);
+
+	tft.drawRect(0, 30, tft.getDisplayXSize()-1, 30);
+	tft.drawRect(0, 100, tft.getDisplayXSize()-1, 100);
+	tft.drawRect(0, 170, tft.getDisplayXSize()-1, 170);
+	tft.drawRect(0, 240, tft.getDisplayXSize()-1, 240);
 }

 void drawDepth(float depth) {
-	//TODO
+	if (currentScreen == GAUGE_SCREEN) {
+		tft.setFont(SevenSegNumFont);
+		tft.setColor(VGA_AQUA);
+		tft.printNumI(depth, CENTER, 50, 3, '0');
+	}
 }

 void drawMaximumDepth(float maximumDepth) {
@@ -429,11 +494,20 @@
 }

 void drawCurrentTemperature(float currentTemperature) {
-	//TODO
+	if (currentScreen == GAUGE_SCREEN) {
+		tft.setFont(SevenSegNumFont);
+		tft.setColor(VGA_AQUA);
+		tft.printNumI(currentTemperature, CENTER, 120, 2);
+	}
+
 }

 void drawCurrentPressure(int currentPressure) {
-	//TODO
+	if (currentScreen == GAUGE_SCREEN) {
+		tft.setFont(SevenSegNumFont);
+		tft.setColor(VGA_AQUA);
+		tft.printNumI(currentPressure, CENTER, 190, 4);
+	}
 }

 void drawOxigenPercentage(int oxigenPercentage) {


Call WiFi.mode(WIFI_STA) in setup()

Call WiFi.mode(WIFI_STA) in setup()

Explicitly set the wifi mode in setup() to prevent the ESP8266 from operating (by default) as both AP and STA.

--- GarHAge.ino
+++ GarHAge.ino
@@ -75,6 +75,7 @@
   Serial.print("Connecting to ");
   Serial.println(ssid);

+  WiFi.mode(WIFI_STA);
   WiFi.begin(ssid, password);

   if (static_ip) {


Removed unwanted data

Removed unwanted data

--- MID/MID.ino
+++ MID/MID.ino
@@ -1,33 +1,25 @@
+/*
+---------------------------------------------------
+    Arduino MID
+
+     Author: Angel Zaprianov <me@fire1.eu>
+     Version: 0.1 [pre-alpha]
+     Start Date: 09.06.2016
+
+     For the full copyright and license information, please view the LICENSE
+     file that was distributed with this source code.
+---------------------------------------------------
+
+ MID function menu
+*/
+
 #include <Arduino.h>
 #include <SPI.h>
 #include <OneWire.h>
 #include <MenuBackend.h>
 #include <DallasTemperature.h>
 #include <SoftwareSerial.h>
-//
-// ArduinoDroid build
-//      @deprecated since IDE wrongly handled the sourcecode
-//      path to internal storage:
-//          /storage/emulated/0/ArduinoDroid/sketchbook/ArduinoMid/MID/lib/
-//
-// #define IDE_ARDUINO_DROID // Uncomment to use ArduinoDroid IDE for upload
-
-
-/*
----------------------------------------------------
-    Arduino MID
-
-     Author: Angel Zaprianov <me@fire1.eu>
-     Version: 0.1 [pre-alpha]
-     Start Date: 09.06.2016
-
-     For the full copyright and license information, please view the LICENSE
-     file that was distributed with this source code.
----------------------------------------------------
-
- MID function menu
-
-*/
+
 #define SERIAL_INJECT_DATA
 //
 // Uncommented to debug basics
@@ -37,9 +29,9 @@
 #define MILLIS_SENS 200
 //
 // Time information
-#define MILLIS_PER_HR    3600000 // Hour
-#define MILLIS_PER_MN    60000    // Minute
-#define MILLIS_PER_SC    1000    // Second
+#define MILLIS_PER_HR    3600000    // Hour
+#define MILLIS_PER_MN    60000      // Minute
+#define MILLIS_PER_SC    1000       // Second

 //
 // Inside temperature [very cheep temperature sensor]
@@ -50,28 +42,28 @@
 // MID plug pins definition over Arduino
 //
 // Define button pins for steering controller
-const uint8_t BTN_PIN_UP = 8;
-const uint8_t BTN_PIN_DW = 9;
+const uint8_t BTN_PIN_UP = 8;       //  Plug:23     Column switch
+const uint8_t BTN_PIN_DW = 9;       //  Plug:24     Column switch navigation
 //
 // Shutdown protection pin
-const uint8_t SAV_PIN_CTR = A6; //
-const uint8_t SAV_PIN_DTC = A7; //
+const uint8_t SAV_PIN_CTR = A6;     //  Plug:4      Disconnect supply voltage
+const uint8_t SAV_PIN_DTC = A7;     //  Plug:16     Detect ignition key off state
 //
 // Engine pins
-const uint8_t ENG_CLT_PIN = A0; // Engine Temp. MID32 RPM [attachInterrupt]
-const uint8_t RPM_SNS_PIN = 2;  //  old:10 MID6 RPM [attachInterrupt]
-const uint8_t SPD_SNS_PIN = 3;  //  MID12 Speed sensor hub [attachInterrupt]
-const uint8_t ECU_SGN_PIN = 19; //  ECU signal
+const uint8_t ENG_CLT_PIN = A0;     //  Plug:31     Engine Temp.  [attachInterrupt]
+const uint8_t RPM_SNS_PIN = 2;      //  Plug:6      RPM [attachInterrupt]
+const uint8_t SPD_SNS_PIN = 3;      //  Plug:12     Speed sensor hub [attachInterrupt]
+const uint8_t ECU_SGN_PIN = 19;     //  Plug:27     ECU  signal
 //
 // lpg old pin: A4
-const uint8_t LPG_LVL_PIN = A5; // testing for serial
+const uint8_t LPG_LVL_PIN = A5;     //  None        Fuel LPG switch
 //
 // Display dim pins
-const uint8_t DIM_PIN_VAL = A10; // MID7 input Dim of lcdDisplay
-const uint8_t DIM_PIN_OUT = 46; // output dim of lcdDisplay
+const uint8_t DIM_PIN_VAL = A10;    //  Plug:7      Display back-light
+const uint8_t DIM_PIN_OUT = 46;     //              Output dim of lcdDisplay
 //
 // Temperatures
-const uint8_t TMP_PIN_OUT = A9; // External temperature sensor
+const uint8_t TMP_PIN_OUT = A9;     // Plug:3       External temperature sensor

 /* Extras ...   ******/
 //
@@ -97,10 +89,6 @@
 // LiquidCrystal library
 // Including from Arduino IDE
 #include <LiquidCrystal.h>
-
-
-#ifndef IDE_ARDUINO_DROID
-
 //
 // Interval / Amplitude
 #include "lib/IntAmp.h"
@@ -122,27 +110,10 @@
 //
 //
 #include "lib/EepRom.h"
-
 //
 // Add library
 #include "lib/ShutDw.h"

-#else
-
-//
-// Interval / Amplitude
-#include "/storage/emulated/0/ArduinoDroid/sketchbook/ArduinoMid/MID/lib/IntAmp.h"
-//
-// Adding Alphine emulator
-#include "/storage/emulated/0/ArduinoDroid/sketchbook/ArduinoMid/MID/lib/WhlSens.h"
-//
-// Main Sensor handler
-#include "/storage/emulated/0/ArduinoDroid/sketchbook/ArduinoMid/MID/lib/MainFunc.h"
-//
-// Engine sensors
-#include "/storage/emulated/0/ArduinoDroid/sketchbook/ArduinoMid/MID/lib/CarSens.h"
-
-#endif
 //
 // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7)
 LiquidCrystal lcd(32, 33, 34, 35, 36, 37);
@@ -162,33 +133,18 @@
 //
 // Menu
 MidMenu midMenu(&ampInt, &whlSens, &carSens);
-
 //
 // Data storage
 EepRom eepRom(&carSens);
-
-
 //
 // Shutdown constructor
 ShutDw shutDown(&eepRom, &ampInt, &carSens);
-
-#ifndef IDE_ARDUINO_DROID
 //
 // Special characters
 #include "lib/LcdChar.h"
 //
 // Display driver
 #include "lib/Lcd16x2.h"
-
-#else
-//
-// Special characters
-#include "/storage/emulated/0/ArduinoDroid/sketchbook/ArduinoMid/MID/lib/LcdChar.h"
-//
-// Display driver
-#include "/storage/emulated/0/ArduinoDroid/sketchbook/ArduinoMid/MID/lib/Lcd16x2.h"
-
-#endif

 //
 // Define Welcome screen


Adding ROS initialization code.

Adding ROS initialization code.

--- src/ExcavatorDriverROS/ExcavatorDriverROS.ino
+++ src/ExcavatorDriverROS/ExcavatorDriverROS.ino
@@ -216,12 +216,15 @@

 void setup()
 {
+  // Initialize ROS stuff
+  excavatorNode.initNode();
+  excavatorNode.subscribe(commandSubscriber);
   // Initialize the serial connection to the saberteeth
   Serial3.begin(9600);
   // Stop all the motors, if they were moving.
   // This must be done AFTER stopping all the motors.
   stopAllMotors();
-  unitTest();
+  //unitTest();
 }

 void loop()


Changed Baud Rate to 230400

Changed Baud Rate to 230400

--- BitBangingMpu6050/LeftHand.ino
+++ BitBangingMpu6050/LeftHand.ino
@@ -775,7 +775,7 @@

   // Clear the 'sleep' bit to start the sensor.
   MPU6050_write_reg (MPU6050_PWR_MGMT_1, 0);
-      mySerial.begin(115200);
+      mySerial.begin(230400);
       Serial.println("Starting");
       mySerial.println("Starting Bluetooth Module");
       calibrate_sensor1();
@@ -810,23 +810,23 @@
       }
       if(flag==7)
       {
-        mpunumber2();
+       // mpunumber2();
         //delay(1000);
       }
        if(flag==8)
        {
-        mpunumber3();
+       // mpunumber3();
         //delay(1000);
       }
        if(flag==9)
         {
-        mpunumber4();
+        //mpunumber4();
         //delay(1000);
       }

        if(flag==10)
        {
-        mpunumber5();
+       // mpunumber5();
         flag=6;
         //delay(1000);
       }


cleaned up and removed unessary variables

--- Arduino/sketches/Sensor_Module/Sensors.ino
+++ Arduino/sketches/Sensor_Module/Sensors.ino
@@ -1,38 +1,16 @@
-/*#include <avr/eeprom.h>
-// to define in main program setup
-static uint16_t calibratingG;
-static int16_t  gyroADC[3],accADC[3],accSmooth[3],magADC[3];
-static int16_t gyroZero[3] = {0,0,0};
-static uint16_t acc_1G;             // this is the 1G measured acceleration
-static uint16_t calibratingA = 0;  // the calibration is done in the main loop. Calibrating decreases at each cycle down to 0, then we enter in a normal mode.
-static int16_t lookupPitchRollRC[6];// lookup table for expo & RC rate PITCH+ROLL
-static int16_t lookupThrottleRC[11];// lookup table for expo & mid THROTTLE
-static int16_t  acc_25deg;
-*/
-#define MINTHROTTLE 1150
-#define MAXTHROTTLE 1850
+// Sensor.ino
+
 #define GYRO 1
 #define ACC 1

 #define ROLL       0
 #define PITCH      1
 #define YAW        2
-#define PIDITEMS 10

 static struct {
   uint8_t checkNewConf;
-  uint8_t P8[PIDITEMS], I8[PIDITEMS], D8[PIDITEMS];
-  uint8_t rcRate8;
-  uint8_t rcExpo8;
-  uint8_t rollPitchRate;
-  uint8_t yawRate;
-  uint8_t dynThrPID;
-  uint8_t thrMid8;
-  uint8_t thrExpo8;
   int16_t accZero[3];
-  int16_t magZero[3];
   int16_t angleTrim[2];
-  uint8_t powerTrigger1;
   #if defined(GYRO_SMOOTHING)
     uint8_t Smoothing[3];
   #endif
@@ -336,25 +314,8 @@
 void writeParams(uint8_t b) {
   conf.checkNewConf = EEPROM_CONF_VERSION; // make sure we write the current version into eeprom
   eeprom_write_block((const void*)&conf, (void*)0, sizeof(conf));
-  readEEPROM();
+  //readEEPROM();
   //if (b == 1) blinkLED(15,20,1);
-}
-
-void readEEPROM() {
-  uint8_t i;
-
-  eeprom_read_block((void*)&conf, (void*)0, sizeof(conf));
-  for(i=0;i<6;i++) {
-    lookupPitchRollRC[i] = (2500+conf.rcExpo8*(i*i-25))*i*(int32_t)conf.rcRate8/2500;
-  }
-  for(i=0;i<11;i++) {
-    int16_t tmp = 10*i-conf.thrMid8;
-    uint8_t y = 1;
-    if (tmp>0) y = 100-conf.thrMid8;
-    if (tmp<0) y = conf.thrMid8;
-    lookupThrottleRC[i] = 10*conf.thrMid8 + tmp*( 100-conf.thrExpo8+(int32_t)conf.thrExpo8*(tmp*tmp)/(y*y) )/10; // [0;1000]
-    lookupThrottleRC[i] = MINTHROTTLE + (int32_t)(MAXTHROTTLE-MINTHROTTLE)* lookupThrottleRC[i]/1000;            // [0;1000] -> [MINTHROTTLE;MAXTHROTTLE]
-  }
 }
 // ************************************************************************************************************

@@ -396,8 +357,6 @@
 }

 // ************************************************************************************************************
-
-
 void initSensors() {
   delay(200);
   delay(100);


removed roll and heading to try and get the write speed up. Current Write Speed: 10.8Hz over 90s

--- Calibration/liveCode/overclockAccel/overclockAccel.ino
+++ Calibration/liveCode/overclockAccel/overclockAccel.ino
@@ -18,7 +18,7 @@
 sensors_event_t accel_event;
 sensors_vec_t   orientation;
 //data buffer for the accel and orientation readings
-String dataString;
+char dataString[60];

 void initAccel()
 {
@@ -65,9 +65,12 @@
   accel.getEvent(&accel_event);
   if (dof.accelGetOrientation(&accel_event, &orientation))
   {
-    dataString = ((String) accel_event.acceleration.x) + ((String)accel_event.acceleration.y) + ((String)accel_event.acceleration.z)
-      + ((String)accel_event.orientation.roll) + ((String)accel_event.orientation.pitch) + ((String) accel_event.orientation.heading) + millis() + '\n';
-    sdWrite(dataString);
+    sdWrite((String) accel_event.acceleration.x);
+    sdWrite((String) accel_event.acceleration.y);
+    sdWrite((String) accel_event.acceleration.z);
+    sdWrite((String) accel_event.orientation.roll);
+    sdWrite((String) millis());
+    sdWriteNewline();
   }
 }
 bool sdWriteNewline() {


Emit what function is ready

Emit what function is ready

It gets confusing otherwise if some key gets pressed mistakenly and an
unknown function is started.

--- Programmer/Programmer.ino
+++ Programmer/Programmer.ino
@@ -147,7 +147,7 @@
   // Initialise control pins
   progSetup();

-  Serial.println("READY");
+  Serial.println("READY FLASH");
   if (!Serial.find("GO\n")) {
     Serial.println("TIMEOUT");
     return;
@@ -252,7 +252,7 @@
 void read_infopage() {
   progSetup();

-  Serial.println("READY");
+  Serial.println("READY READ INFOPAGE");
   // Wait for GO command from Serial
   while (!Serial.find("GO")) {
     Serial.println("READY");
@@ -287,7 +287,7 @@
 void read_mainpage() {
   progSetup();

-  Serial.println("READY");
+  Serial.println("READY READ MAINPAGE");
   // Wait for GO command from Serial
   while (!Serial.find("GO")) {
     Serial.println("READY");
@@ -343,7 +343,7 @@
 void restore_infopage() {
   progSetup();

-  Serial.println("READY");
+  Serial.println("READY RESTORE INFOPAGE");
   while (!Serial.find("GO")) {
     Serial.println("READY");
   };


fix critical issue

fix critical issue

--- firmware/harp-communicator/harp-communicator.ino
+++ firmware/harp-communicator/harp-communicator.ino
@@ -4,21 +4,23 @@
 Laser* lasers[NUMBER_OF_LASERS];

 void setup() {
-  for (int i = 0; i = NUMBER_OF_LASERS; i++) {
+  Serial.begin(9600);
+  for (int i = 0; i < NUMBER_OF_LASERS; i++) {
     // set pins for lasers and sensors
-    int sensorPin = i + 28; // this index may be wrong
-    int laserPin = i + 2; // this one too
+    int sensorPin = i + 29; // this index may be wrong
+    int laserPin = i + 3; // this one too
+    Serial.println(laserPin);
     pinMode(laserPin, OUTPUT);
     pinMode(sensorPin, INPUT);
     digitalWrite(laserPin, HIGH);
     lasers[i] = new Laser(true, false, sensorPin, laserPin);
   }
-  Serial.begin(9600);
 }

 void loop() {
-  for(int i = 0 ; i = NUMBER_OF_LASERS; i++) {
+  for(int i = 0; i < NUMBER_OF_LASERS; i++) {
     lasers[i]->isCrossed = digitalRead(lasers[i]->sensorPin) != HIGH;
     Serial.print(lasers[i]->isCrossed);
   }
+  Serial.println();
 }


Local echo for delete/backspace More displays Page numbers

--- Firmware/SDShell/SDShell.ino
+++ Firmware/SDShell/SDShell.ino
@@ -37,7 +37,6 @@
 //    then: delayed writes for small buffered targets systems
 //    more: word wrap
 //          0d 0a 0d 0a dumps nonprintables
-//          display page number
 //          skip to page number
 //    hex:  Paged?
 //    head <file> <lines>
@@ -48,7 +47,10 @@
 //    pagesize (value)  (with no operand, just displays the value
 //    sd (pin) to pick the sd card to use

-#define VERSION "0.7"
+#define VERSION "0.8"
+// v0.08 2014-04-13 - local echo for backspace/delete
+//                    newlines for "help"
+//                    better "help" spacing
 // v0.07 2014-04-07 - more, echo, in, out implemented
 // v0.06 2014-04-06 - fast LED flash on autobaud wait
 // v0.05 2014-04-05 - Path support for files added
@@ -129,7 +131,8 @@
 static const unsigned char msg_Cmds[]    PROGMEM = "Commands:";
 static const unsigned char msg_Bytes[]   PROGMEM = " bytes.";
 static const unsigned char msg_Files[]   PROGMEM = " Files.";
-static const unsigned char msg_More[]    PROGMEM = " ==[ More ]==";
+static const unsigned char msg_MoreA[]    PROGMEM = " ==[ More (page ";
+static const unsigned char msg_MoreB[]    PROGMEM = ") ]==";
 static const unsigned char msg_EchoOn[]  PROGMEM = "Echo on.";
 static const unsigned char msg_EchoOff[] PROGMEM = "Echo off.";
 static const unsigned char msg_BadPort[] PROGMEM = "Bad port.";
@@ -460,14 +463,25 @@
   do {
     while( !Serial.available() ) idle();
     ch = Serial.read();
-    if( localEcho ) { Serial.write( ch ); }

     // check for backspace
-    if( ch == 0x08 /* backspace character, CTRL-H */ ) {
+    if( ch == 0x08 /* backspace character, CTRL-H */ || ch == 0x7f /* delete on mac, del */ ) {
       if( linelen > 0 ) {
         linelen--;
+        line[linelen] = '\0'; // necessary for local echo re-echo
+
+        if( localEcho ) {
+          // redump echo line
+          Serial.println( "" );
+          prompt();
+          Serial.print( line );
+          Serial.flush();
+        }
       }
+
     } else {
+      if( localEcho ) { Serial.write( ch ); }
+
       line[linelen] = ch;
       linelen++;
     }
@@ -539,27 +553,31 @@
 };
 #define kFcnFlagSD  (0x01)    /* command needs SD card */
 #define kFcnFlagHDR (0x80)    /* fakeo for header */
+#define kFcnFlagNL  (0x40)    /* fakeo for newline */

 struct fcns fcnlist[] =
 {
   // these require SD card
-  { "SD Card", NULL, kFcnFlagHDR },
+  { "SD Card:", NULL, kFcnFlagHDR },
   { "cd", &cmd_cd, kFcnFlagSD },
   { "pwd", &cmd_pwd, kFcnFlagSD },
   { "mkdir", &cmd_mkdir, kFcnFlagSD },
   { "rmdir", &cmd_rmdir, kFcnFlagSD },
+  { "", &cmd_rm, kFcnFlagNL },
   { "ls", &cmd_ls, kFcnFlagSD },
   { "dir", &cmd_ls, kFcnFlagSD },
   { "rm", &cmd_rm, kFcnFlagSD },
   { "del", &cmd_rm, kFcnFlagSD },
+  { "", &cmd_rm, kFcnFlagNL },
   { "capt", &cmd_capture, kFcnFlagSD },
   { "onto", &cmd_onto, kFcnFlagSD },
   { "hex", &cmd_hex, kFcnFlagSD },
   { "type", &cmd_type, kFcnFlagSD },
+  { "cat", &cmd_type, kFcnFlagSD },
   { "more", &cmd_more, kFcnFlagSD },

   // these are for EEProm IO
-  { "EEProm", NULL, kFcnFlagHDR },
+  { "EEProm:", NULL, kFcnFlagHDR },
   { "ecapt", &cmd_ecapture },
   { "eonto", &cmd_eonto },
   { "ehex", &cmd_ehex },
@@ -569,12 +587,12 @@
   { "esave", &cmd_esave },

   // Micro
-  { "Micro", NULL, kFcnFlagHDR },
+  { "Micro IO:", NULL, kFcnFlagHDR },
   { "in", &cmd_in },
   { "out", &cmd_out },

   // Utility
-  { "Utility", NULL, kFcnFlagHDR },
+  { "Utility:", NULL, kFcnFlagHDR },
   { "echo", &cmd_echo },
   { "?", &cmd_help },
   { "help", &cmd_help },
@@ -817,6 +835,7 @@
 void cmd_more( void )
 {
   int linecount = 0;
+  long page = 0;
   int ch, lastch;
   if( argc < 2 ) { cmd_error( kErrNo ); return; }

@@ -844,7 +863,10 @@
         Serial.println();

         if( linecount > kPageSize ) {
-          printmsg( msg_More );
+          printmsgNoNL( msg_MoreA );
+          Serial.print( page++, DEC );
+          printmsg( msg_MoreB );
+
           bool waitForInput = true;
           while( waitForInput ) {
             while( !Serial.available() && digitalRead( kButton ) != LOW ) { idle(); }
@@ -1155,14 +1177,21 @@
   int i=0;
   int items = 0;
   while( fcnlist[i].name ) {
-    if( fcnlist[i].flags & kFcnFlagHDR ) {
+
+    if( fcnlist[i].flags & kFcnFlagNL ) {
       items = 0;
+    } else if( fcnlist[i].flags & kFcnFlagHDR ) {
       Serial.println( "" );
-      Serial.println( fcnlist[i].name );
+      Serial.print( fcnlist[i].name );
+      items = 0;
     } else {
-      if( 0 == (items % 0)) { Serial.print( "   " ); }
-      Serial.print( fcnlist[i].name );
-      Serial.print( " \t" );
+      if( 0 == (items % 0)) {
+        Serial.println( "" );
+        Serial.print( "   " );
+      }
+      sprintf( (char*)buf, "%-6s ",  fcnlist[i].name );
+
+      Serial.print( buf );
       items++;
     }
     i++;
@@ -1208,13 +1237,17 @@
 // main loop entry point

 bool showPrompt = true;
+void prompt()
+{
+    Serial.print( "> " );
+    Serial.flush();
+}

 void loop()
 {
   // nothing happens after setup finishes.
   if( showPrompt ) {
-    Serial.print( "> " );
-    Serial.flush();
+    prompt();
   }

   getLine();


whitespace fix

whitespace fix

--- Thermostat/Thermostat.ino
+++ Thermostat/Thermostat.ino
@@ -21,7 +21,7 @@

 volatile float temperatureInF;

-LedDisplay ledDisplay(segmentShiftRegisterClockPin, registerClockPin, whichSegmentDataPin,digitShiftRegisterClockPin, registerClockPin, whichDigitDataPin);
+LedDisplay ledDisplay(segmentShiftRegisterClockPin, registerClockPin, whichSegmentDataPin, digitShiftRegisterClockPin, registerClockPin, whichDigitDataPin);
 AsyncTemperatureSensor sensor(temperatureSensorPin);

 void setup()


improvement to forward stop backout turn with two turn directions

--- _03_s4a_edu_forward_and_turn/_03_s4a_edu_forward_and_turn.ino
+++ _03_s4a_edu_forward_and_turn/_03_s4a_edu_forward_and_turn.ino
@@ -26,24 +26,33 @@

   doBlink(10, 100);

-  setMotor(MOTOR_LEFT, MOTOR_DIRECTION_FORWARD, 100);
-  setMotor(MOTOR_RIGHT, MOTOR_DIRECTION_BACKWARDS, 100);
+  rotateLeft();
+  delay(3000);
+  rotateRight();
+  delay(3000);

-  delay (5000);
+  doBlink(3, 500);
 }

 // the loop function runs over and over again forever
 void loop() {
-  setMotor(MOTOR_LEFT, MOTOR_DIRECTION_FORWARD, 100);
-  setMotor(MOTOR_RIGHT, MOTOR_DIRECTION_FORWARD, 100);
-  delay(3000);
-  setMotor(MOTOR_LEFT, MOTOR_DIRECTION_FORWARD, 0);
-  setMotor(MOTOR_RIGHT, MOTOR_DIRECTION_FORWARD, 0);
-  doBlink(3, 100);
-  setMotor(MOTOR_LEFT, MOTOR_DIRECTION_BACKWARDS, 100);
-  setMotor(MOTOR_RIGHT, MOTOR_DIRECTION_FORWARD, 100);
-  delay(1000);
+  moveForward();
+  doBlink(4,500);
+  stopMotors();
+  doBlink(3, 50);
+  moveBackwards();
+  doBlink(2,100);
+  rotateLeft();
+  doBlink(2, 250);

+  moveForward();
+  doBlink(3,500);
+  stopMotors();
+  doBlink(3, 50);
+  moveBackwards();
+  doBlink(2,100);
+  rotateRight();
+  doBlink(2, 250);
 }

 /*
@@ -64,6 +73,30 @@
   }
 }

+void moveForward(){
+  setMotor(MOTOR_LEFT, MOTOR_DIRECTION_FORWARD, 100);
+  setMotor(MOTOR_RIGHT, MOTOR_DIRECTION_FORWARD, 100);
+}
+
+void moveBackwards(){
+  setMotor(MOTOR_LEFT, MOTOR_DIRECTION_BACKWARDS, 100);
+  setMotor(MOTOR_RIGHT, MOTOR_DIRECTION_BACKWARDS, 100);
+}
+
+void rotateRight(){
+  setMotor(MOTOR_LEFT,  MOTOR_DIRECTION_FORWARD, 100);
+  setMotor(MOTOR_RIGHT, MOTOR_DIRECTION_BACKWARDS, 100);
+}
+void rotateLeft(){
+  setMotor(MOTOR_LEFT,  MOTOR_DIRECTION_BACKWARDS, 100);
+  setMotor(MOTOR_RIGHT, MOTOR_DIRECTION_FORWARD, 100);
+}
+
+void stopMotors(){
+  setMotor(MOTOR_LEFT, MOTOR_DIRECTION_FORWARD, 0);
+  setMotor(MOTOR_RIGHT, MOTOR_DIRECTION_FORWARD, 0);
+}
+
 //USE THIS AS HUMANCOMMUNICATION MECHANISM
 void doBlink(int times, int delayTime){
   for(int i=0; i<times; i++){


Fix alarm start.

Fix alarm start.

--- examples/Time/CosaAlarm/CosaAlarm.ino
+++ examples/Time/CosaAlarm/CosaAlarm.ino
@@ -28,8 +28,8 @@
 #include "Cosa/IOStream/Driver/UART.hh"

 // Configuration: RTC or External Interrupt Clock Source
-// #define USE_ALARMS_SCHEDULER
-#define USE_CLOCK_SCHEDULER
+#define USE_ALARMS_SCHEDULER
+// #define USE_CLOCK_SCHEDULER

 // Use the alarm scheduler (trigged by the real-time clock scheduler)
 #if defined(USE_ALARMS_SCHEDULER)
@@ -88,7 +88,7 @@
   // Start the real-time clock and alarm scheduler
   RTC::begin();
   RTC::job(&scheduler);
-  alarms.begin();
+  alarms.Job::start();
 #endif

 #if defined(USE_CLOCK_SCHEDULER)


Update ArduinoShield.ino

Update ArduinoShield.ino

--- OpenEnergyMonitor/ArduinoShield/ArduinoShield.ino
+++ OpenEnergyMonitor/ArduinoShield/ArduinoShield.ino
@@ -1 +1,166 @@
-Sketch
+/*
+  LeoShieldCT1234v3.ino with DS18B20 option from:
+  https://github.com/openenergymonitor/emontx-shield/blob/master/firmware/Shield_CT1234_Voltage_SerialOnly/Shield_CT1234_Voltage_SerialOnly.ino
+  EmonTx CT123 Voltage Serial Only example
+  Part of the openenergymonitor.org project
+  Licence: GNU GPL V3
+  Author: Trystan Lea and minor mods by ESPproMon©
+*/
+
+#include "EmonLib.h"
+
+EnergyMonitor ct1,ct2,ct3,ct4;  // Create  instances for each CT channel
+bool DEBUG = 1;                 // Print serial debug
+bool TTLAVAILABLE = 1;          // Send data via TTL on Serial1 of Leonardo - maybe Software Serial TODO for Uno
+
+#include <OneWire.h>                    //http://www.pjrc.com/teensy/td_libs_OneWire.html
+#include <DallasTemperature.h>          //http://download.milesburton.com/Arduino/MaximTemperature/DallasTemperature_LATEST.zip
+const int TEMPERATURE_PRECISION=  11;   //9 (93.8ms),10 (187.5ms) ,11 (375ms) or 12 (750ms) bits equal to resplution of 0.5C, 0.25C, 0.125C and 0.0625C
+const byte MaxOnewire=             2;   // assume no more than 2 sensors
+#define ASYNC_DELAY 375                 // DS18B20 conversion delay - 9bit requres 95ms, 10bit 187ms, 11bit 375ms and 12bit resolution takes 750ms
+#define ONE_WIRE_BUS               4    // DS18B20 Data
+int temp[MaxOnewire];
+//-------------------------------------------------------------------------------------------------------------------------------------------
+
+//Setup DS128B20
+bool DS18B20_STATUS;
+OneWire oneWire(ONE_WIRE_BUS);
+DallasTemperature sensors(&oneWire);
+byte allAddress [MaxOnewire][8];  // 8 bytes per address
+byte numSensors;
+
+//-------------------------------------------------------------------------------------------------------------------------------------------
+
+const int LEDpin = 9; // On-board emonTx LED
+
+typedef struct {
+  int temp[MaxOnewire];
+  unsigned long pulseCount;
+} PayloadTX;     // create structure - a neat way of packaging data for RF comms
+
+PayloadTX emontx;
+
+void setup()
+{
+  Serial.begin(115200);
+  //while (!Serial) {}   // wait for serial port to connect. Normally for Leonardo but not needed
+  Serial.println("emonTX Shield CT1234 with Voltage & DS18B20 - Serial Only example");
+  Serial.println("OpenEnergyMonitor.org");
+  Serial1.begin(115200); // start TTL
+  // Calibration factor = CT ratio / burden resistance = (100A / 0.05A) / 33 Ohms = 60.606
+  ct1.current(1, 60.606); // range of 58.18 to 63.02 for shield and default x with range 86.35 – 95.45 emonTx
+  ct2.current(2, 60.606);
+  ct3.current(3, 60.606);
+  ct4.current(4, 60.606);
+
+  /* (ADC input, calibration, phase_shift)  // use CalVRef.ino sketch to get READVCC_CALIBRATION_CONST 1115000L for Leonardo
+  default normally: ct1.voltage(0, 300.6, 1.7);         // Robert thinks new CT's might need 1.85
+  */
+  ct1.voltage(0, 268.8, 1.25);          // phase 1.7 default is calculated by comparing real and apparent with 100% PF device
+  ct2.voltage(0, 265.8, 1.25);
+  ct3.voltage(0, 265.8, 1.25);          // 268 97 per https://learn.openenergymonitor.org/electricity-monitoring/ctac/calibration
+  ct4.voltage(0, 265.8, 1.25);
+
+  // Setup indicator LED
+  pinMode(LEDpin, OUTPUT);
+  digitalWrite(LEDpin, HIGH);
+
+  //################################################################################################################################
+  //Setup and test for presence of DS18B20
+  //################################################################################################################################
+
+  sensors.begin();
+  sensors.setWaitForConversion(false);             // disable automatic temperature conversion to reduce time spent awake, conversion will be implemented manually in sleeping
+                                                   // http://harizanov.com/2013/07/optimizing-ds18b20-code-for-low-power-applications/
+  numSensors=(sensors.getDeviceCount());
+  if (numSensors > MaxOnewire) numSensors=MaxOnewire;   //Limit number of sensors to max number of sensors
+
+  byte j=0;                                        // search for one wire devices and
+                                                   // copy to device address arrays.
+  while ((j < numSensors) && (oneWire.search(allAddress[j])))  j++;
+
+  if (numSensors==0) DS18B20_STATUS=0;
+    else DS18B20_STATUS=1;
+
+  //################################################################################################################################
+
+  if (DS18B20_STATUS==1) {
+    Serial.print("Detected Temp Sensors: ");
+    Serial.println(numSensors);
+  } else {
+    Serial.println("No temperature sensor");
+  }
+
+  Serial.print("CT1 CT2 CT3 CT4 VRMS PULSE");
+
+  if (DS18B20_STATUS==1){Serial.print(" Temperature 1-"); Serial.print(numSensors);}
+
+  for(byte j=0;j<MaxOnewire;j++)
+      emontx.temp[j] = 3000;      // If no temp sensors connected default to status code 3000
+                                    // will appear as 300 once multipled by 0.1 in emonhub
+  Serial.println();
+
+}
+
+void loop()
+{
+  // Calculate all. No.of crossings, time-out
+  ct1.calcVI(20,2000);
+  ct2.calcVI(20,2000);
+  ct3.calcVI(20,2000);
+  ct4.calcVI(20,2000);
+
+  if (DS18B20_STATUS==1)
+  {
+    for(int j=0;j<numSensors;j++)
+      sensors.setResolution(allAddress[j], TEMPERATURE_PRECISION);                    // and set the A to D conversion resolution of each.
+    sensors.requestTemperatures();
+    for(byte j=0;j<numSensors;j++)
+      emontx.temp[j]=get_temperature(j);
+  }
+
+   if (DEBUG==1) {
+    Serial.print("ct1:");   Serial.print(int(ct1.realPower * 100));
+    Serial.print(",ct2:");  Serial.print(int(ct2.realPower * 100));
+    Serial.print(",ct3:");  Serial.print(int(ct3.realPower * 100));
+    Serial.print(",ct4:");  Serial.print(int(ct4.realPower * 100));
+    Serial.print(",vrms:"); Serial.print(int(ct1.Vrms * 100));
+    Serial.print(",pulse:");Serial.print(emontx.pulseCount);
+    if (DS18B20_STATUS==1){
+      for(byte j=0;j<numSensors;j++){
+        Serial.print(",t"); Serial.print(j); Serial.print(":");
+        Serial.print(emontx.temp[j]);
+      }
+    }
+    Serial.println();
+    delay(50);
+  }
+
+   if (TTLAVAILABLE==1) {
+    Serial1.print("ct1:");   Serial1.print(int(ct1.realPower * 100));
+    Serial1.print(",ct2:");  Serial1.print(int(ct2.realPower * 100));
+    Serial1.print(",ct3:");  Serial1.print(int(ct3.realPower * 100));
+    Serial1.print(",ct4:");  Serial1.print(int(ct4.realPower * 100));
+    Serial1.print(",vrms:"); Serial1.print(int(ct1.Vrms * 100));
+    Serial1.print(",pulse:");Serial1.print(emontx.pulseCount);
+    if (DS18B20_STATUS==1){
+      for(byte j=0;j<numSensors;j++){
+        Serial1.print(",t"); Serial1.print(j); Serial1.print(":");
+        Serial1.print(emontx.temp[j]);
+      }
+    }
+    Serial1.println();
+    delay(50);
+  }
+
+  // Available properties: ct1.realPower, ct1.apparentPower, ct1.powerFactor, ct1.Irms and ct1.Vrms
+  delay(1500);
+  //delay(5000);
+}
+
+
+int get_temperature(byte sensor)
+{
+  float temp=(sensors.getTempC(allAddress[sensor]));
+  if ((temp<125.0) && (temp>-55.0)) return(temp*10);   //if reading is within range for the sensor convert float to int ready to send via TTL
+}


Working solution for Arduino Mega

Working solution for Arduino Mega

--- mwsLCDI2C/mwsLCDI2C.ino
+++ mwsLCDI2C/mwsLCDI2C.ino
@@ -513,11 +513,11 @@

   lcd.clear();
   lcd.print(F("H:"));
-  lcd.print(myHumidity.readHumidity());
+  lcd.print(myHumidity.readHumidity(),2);
   lcd.print(F(" %"));
   lcd.setCursor(0, 2);
   lcd.print(F("T:"));
-  lcd.print(myPressure.readTemp());
+  lcd.print(myPressure.readTemp(),2);
   lcd.print(F(" C"));
   delay(5000);

@@ -528,7 +528,7 @@
   lcd.print("(mm/d)");
   lcd.setCursor(0, 2);
   lcd.print(F("P:"));
-  lcd.print(myPressure.readPressure()/100.0);
+  lcd.print(myPressure.readPressure()/100.0,2);
   lcd.print(F(" hPa"));
   delay(5000);


fixed isp_capture sketch after MemoryPlug API arg order change

--- examples/Ports/isp_capture/isp_capture.ino
+++ examples/Ports/isp_capture/isp_capture.ino
@@ -610,7 +610,7 @@

 static void showInfo () {
     // restore parameters from page 0
-    mem.load(0, &param, 0, sizeof param);
+    mem.load(0, 0, &param, sizeof param);
     // report saved info for debugging
     Serial.print("ISP bytes: ");
     Serial.println(param.programsize);
@@ -655,7 +655,7 @@
     if (doneTimer.poll()) {
         recordFlush();
         param.programsize = stream.position(1); // save parameter info in page 0
-        mem.save(0, &param, 0, sizeof param);
+        mem.save(0, 0, &param, sizeof param);

         setLed(1);
         delay(100);


内部処理を見直し 電源シーケンス見直し バッテリー残量警告追加

内部処理を見直し
電源シーケンス見直し
バッテリー残量警告追加

--- Hardware/Arduino/Tsubuta_AddOnBoard/Tsubuta_AddOnBoard.ino
+++ Hardware/Arduino/Tsubuta_AddOnBoard/Tsubuta_AddOnBoard.ino
@@ -8,89 +8,6 @@
 #include <EEPROM.h>
 #include <Wire.h>

-// --------------------------------------
-//   Version Information
-// --------------------------------------
-#define VERSION 0x0001
-
-#define INTERVAL_TIME   60*15   // default interval : 15min
-
-// --------------------------------------
-//   EEPROM defenision
-// --------------------------------------
-//    00h              -- Version. if 0xff, value is not set.
-//    01h              -- Power On Mode : 0 - auto power off / 1 : auto power on
-//    02h/03h/04h/05h  -- Interval Timer Count
-//    06h              -- GPIO0 Setting 0:Out / 1:In / 2:In-Pullup
-//    07h              -- GPIO1 Setting 0:Out / 1:In / 2:In-Pullup
-//    08h              -- GPIO2 Setting 0:Out / 1:In / 2:In-Pullup
-//    09h              -- GPIO3 Setting 0:Out / 1:In / 2:In-Pullup
-
-// ---------------------------------------
-//     for I2C
-// ---------------------------------------
-#define I2C_SLAVE_ADDRESS   8
-
-
-// ---------------------------------------
-//     for UART
-// ---------------------------------------
-#define UART_BAUDRATE     115200
-
-// ---------------------------------------
-//     ピン定義
-// ---------------------------------------
-#define TSUBUTA_UART_RXD  0     //  PD0
-#define TSUBUTA_UART_TXD  1     //  PD1
-
-#define TSUBUTA_RPIPOWER  3     //  PD3 (O)  Raspberry Pi Power On/Off
-#define TSUBUTA_GPI_POFF  4     //  PD4 (I) Shutdown signal from Raspberry Pi
-
-#define TSUBUTA_GPIO0     5     //  PD5  PWM
-#define TSUBUTA_GPIO1     6     //  PD6  PWM
-#define TSUBUTA_GPIO2     7     //  PD7
-#define TSUBUTA_GPIO3     8     //  PB0
-
-#define TSUBUTA_RPI_INT   9     //  PB1 (O) Interrupt signal to Raspberry Pi
-#define TSUBUTA_RTC_INT   10    //  PB2 (I) Interrupt signal from DS1307(RTC Clock)
-
-#define TSUBUTA_AD0       0     //  PC0
-#define TSUBUTA_AD1       1     //  PC1
-#define TSUBUTA_AD2       2     //  PC2
-#define TSUBUTA_AD3       3     //  PC3
-
-#define LED_PIN     13
-
-// ------- Command
-#define COMMAND_GETINFO           0x00
-#define COMMAND_SETINTERVALTIME   0x01
-#define COMMAND_POWEROFF          0x02
-#define COMMAND_LOAD_SETTING      0x0E
-#define COMMAND_SAVE_SETTING      0x0F
-
-#define COMMAND_SETGPIO1          0x10
-#define COMMAND_SETGPIO2          0x11
-#define COMMAND_SETGPIO3          0x12
-#define COMMAND_SETGPIO4          0x13
-
-#define COMMAND_SET_GPO1          0x20
-#define COMMAND_SET_GPO2          0x21
-#define COMMAND_SET_GPO3          0x22
-#define COMMAND_SET_GPO4          0x23
-
-#define COMMAND_GET_GPI1          0x30
-#define COMMAND_GET_GPI2          0x31
-#define COMMAND_GET_GPI3          0x32
-#define COMMAND_GET_GPI4          0x33
-
-#define COMMAND_GET_ADC1          0x40
-#define COMMAND_GET_ADC2          0x41
-#define COMMAND_GET_ADC3          0x42
-#define COMMAND_GET_ADC4          0x43
-
-#define COMMAND_UNKNOWN           0xFF
-
-
 // ------- for Standby mode
 #ifndef cbi
 #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
@@ -99,45 +16,42 @@
 #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
 #endif

-enum {
-  STATE_STANDBY,    // Standby mode
-  STATE_SLEEP,      // run state when wdt is on.
-  STATE_RUN,        // Full run
-};
-
-enum {
-  RPI_POWER_ON,
-  RPI_POWER_OFF
-};
-
-typedef struct config_info {
-  unsigned char mEEPROMVersion;
-  unsigned char mAutoPowerOnMode;
-  unsigned long mIntervalTime;
-  int           m_GPIO1mode;
-  int           m_GPIO2mode;
-  int           m_GPIO3mode;
-  int           m_GPIO4mode;
-
-  int           m_bPowerStatus;   // RPIの電源ON/OFF状態
-  unsigned long m_lRunTime;       // Arduino側の連続通電時間（秒）
-  unsigned long m_TimerCounter;   // Interval Timer Counter
-  unsigned long m_WdtCounter;     // Watch dog Timer Counter
-
-  bool          m_bPowerOffEventSignaled;   // RPiからのイベント入ったかフラグ
-  bool          m_RTCEventSignaled;         // RTCからのイベント入ったかフラグ
-  bool          m_PowerKeyEventSignaled;
-
-} CONFIG_TSUBUTA;
-
-
+
+#define TSUBUTA_RPIPOWER  3     //  PD3 (O)  Raspberry Pi Power On/Off
+#define TSUBUTA_GPI_POFF  4     //  PD4 (I) Shutdown signal from Raspberry Pi
+
+// ---------------------------------------
+//     for I2C
+// ---------------------------------------
+#define I2C_SLAVE_ADDRESS   8
+
+
+// ------- Command
+#define COMMAND_CLEARTIMER        0x00
+#define COMMAND_SETINTERVALTIME   0x01
+#define COMMAND_POWEROFF          0x02
+#define COMMAND_GET_TIME          0x10
+#define COMMAND_GET_RUN_TIME      0x11
+#define COMMAND_GET_PWRON_CNT     0x12
+
+#define COMMAND_UNKNOWN           0xFF
+
+
+//#define BATTERY_ALERT_THREAD      3000
+#define BATTERY_ALERT_THREAD      180
+
+bool g_bPowerOn = true;
+unsigned long g_PwrOnCount;
+unsigned long g_lRunTime;       // Raspberry Pi側の連続通電時間（秒）
+unsigned long g_TimerCounter;   // Interval Timer Counter
+unsigned long g_WdtCounter;     // Watch dog Timer Counter = Arduino側の連続通電時間（秒）
+unsigned long g_IntervalTime = 900;

 typedef struct _command_info_ {
   unsigned char m_ucCommand;
   unsigned char m_ucLength;
   bool          m_bReply;
 } COMMAND_TABLE;
-

 typedef struct _buffer_tag_ {
   unsigned char   len;
@@ -158,54 +72,15 @@

 volatile RCVCMD g_RcvCmd;

-const int GPIO_PinMappping[] = { 5, 6, 7, 8 };
-const int ADC_PinMappping[] = { 0, 1, 2, 3 };
-
 const COMMAND_TABLE   g_cCommandInfo[] = {
   { 0x00 , 0x01 , true },     // Get Baord Information
   { 0x01 , 0x05 , false },    // Set Interval Timer |
   { 0x02 , 0x01 , false },    // RPi Power Off |
-  { 0x0E , 0x01 , false },    // Load Settings from EEPROM |
-  { 0x0F , 0x01 , false },    // Save settings to EEPROM |
-  { 0x10 , 0x02 , false },    // Set GPIO1 State|
-  { 0x11 , 0x02 , false },    // Set GPIO2 State|
-  { 0x12 , 0x02 , false },    // Set GPIO3 State|
-  { 0x13 , 0x02 , false },    // Set GPIO4 State|
-  { 0x20 , 0x02 , false },    // Set GPO1 H/L |
-  { 0x21 , 0x02 , false },    // Set GPO2 H/L |
-  { 0x22 , 0x02 , false },    // Set GPO3 H/L |
-  { 0x23 , 0x02 , false },    // Set GPO4 H/L |
-  { 0x30 , 0x02 , true },     // Get GPI1 |
-  { 0x31 , 0x02 , true },     // Get GPI2 |
-  { 0x32 , 0x02 , true },     // Get GPI3 |
-  { 0x33 , 0x02 , true },     // Get GPI4 |
-  { 0x40 , 0x01 , true },     // Get ADC1 |
-  { 0x41 , 0x01 , true },     // Get ADC2 |
-  { 0x42 , 0x01 , true },     // Get ADC3 |
-  { 0x43 , 0x01 , true },     //| Get ADC4 |
+  { 0x10 , 0x01 , true },    // RPi Power Off |
+  { 0x11 , 0x01 , true },    // RPi Power Off |
+  { 0x12 , 0x01 , true },    // RPi Power Off |
   { 0xFF , 0xFF, false },
 };
-
-
-
-volatile CONFIG_TSUBUTA  g_stSystemSetting;
-
-// 割り込み内でのイベント管理用
-volatile bool g_bPushPowerButton;           // GPIOに割り当てられたPower Onボタンが押されたフラグ
-volatile bool g_bRequestPowerOffFromRpi;    // RPiからの電源OFF要求(GPIO L->H)
-
-void  system_sleep();                   // システム停止
-void  setup_watchdog(int ii);
-void  setPowDownMode();                  // CPUをパワーダウンモードに設定
-
-void  receiveEvent( int howMany  );
-void  requestEvent( );
-
-void  initSystemSettingInfo( void );
-bool  isAutoPowerOn();
-bool  isTimerDone();
-bool  isRaspberryPiPowerOn();
-void  setRaspberryPiPower( int nMode );

 // ====================================================
@@ -223,7 +98,7 @@
   pPtr->len = 0;
   pPtr->rdptr = 0;
   pPtr->wrptr = 0;
-  memset((void *)pPtr->buff, 0, sizeof(unsigned char)*32 );
+//  memset((void *)pPtr->buff, 0, sizeof(unsigned char)*32 );

   PutBufferStatus(pPtr);
 }
@@ -293,37 +168,19 @@
 }

-//  ---- I2C Command Function
-int  SetGPIOMode( int pin, int mode )
-{
-  int PinMode = -1;
-
-  if ( mode == 0x00 ) {
-    PinMode = INPUT;
-  } else if ( mode == 0x01 ) {
-    PinMode = INPUT_PULLUP;
-  } else if ( mode == 0x02 ) {
-    PinMode = OUTPUT;
-  }
-  if ( PinMode >= 0 ) {
-    pinMode(pin, PinMode );
-    if (PinMode == OUTPUT ) {
-      digitalWrite(pin, LOW);
-    }
-  }
-  return PinMode;
-}
-
-
 void ParseCommand( RCVCMD *pCmd )
 {
   unsigned char ctmp;
   unsigned long ltmp;

   switch( pCmd->ucCmd ) {
-    case COMMAND_GETINFO:
-      Serial.println("CMD:GETINFO");
-      SetCommandBuffer(&g_bufI2CSend, g_stSystemSetting.mEEPROMVersion);
+    case COMMAND_CLEARTIMER:
+      g_TimerCounter = 1;
+      Serial.print("Current Timer Count:");
+      Serial.println(g_TimerCounter);
+      g_TimerCounter = 1;
+      Serial.print("Cleared Timer Count:");
+      Serial.println(g_TimerCounter);
       break;

     case COMMAND_SETINTERVALTIME:
@@ -332,379 +189,37 @@
       ltmp |= pCmd->ucBuff[1]; ltmp <<= 8;
       ltmp |= pCmd->ucBuff[2]; ltmp <<= 8;
       ltmp |= pCmd->ucBuff[3];
-      g_stSystemSetting.mIntervalTime = ltmp;
+      g_IntervalTime = ltmp;
       Serial.print("Interval Time:");
-      Serial.println(g_stSystemSetting.mIntervalTime);
+      Serial.println(g_IntervalTime);
       break;

-    case COMMAND_LOAD_SETTING:
-      Serial.println("CMD:LOADSETTING");
-      LoadSystemSettings();
+    case COMMAND_GET_TIME:
+      Serial.println("CMD:GET_TIME");
+      SetCommandBuffer(&g_bufI2CSend, (g_WdtCounter >> 24) & 0xff );
+      SetCommandBuffer(&g_bufI2CSend, (g_WdtCounter >> 16) & 0xff);
+      SetCommandBuffer(&g_bufI2CSend, (g_WdtCounter >>  8) & 0xff);
+      SetCommandBuffer(&g_bufI2CSend, (g_WdtCounter >>  0) & 0xff);
       break;

-    case COMMAND_SAVE_SETTING:
-      Serial.println("CMD:SAVESETTING");
-      SaveSystemSettings();
+    case COMMAND_GET_RUN_TIME:
+      Serial.println("CMD:GET_RUN_TIME");
+      SetCommandBuffer(&g_bufI2CSend, (g_lRunTime >> 24) & 0xff );
+      SetCommandBuffer(&g_bufI2CSend, (g_lRunTime >> 16) & 0xff);
+      SetCommandBuffer(&g_bufI2CSend, (g_lRunTime >>  8) & 0xff);
+      SetCommandBuffer(&g_bufI2CSend, (g_lRunTime >>  0) & 0xff);
       break;

-    case COMMAND_SETGPIO1:
-      Serial.println("CMD:SETGPIO1_CNF");
-      ltmp = SetGPIOMode(5, pCmd->ucBuff[0] );
-      if ( ltmp >= 0 ) {
-        g_stSystemSetting.m_GPIO1mode = ltmp;
-      }
-      break;
+    case COMMAND_GET_PWRON_CNT:
+      SetCommandBuffer(&g_bufI2CSend, (g_PwrOnCount >> 24) & 0xff );
+      SetCommandBuffer(&g_bufI2CSend, (g_PwrOnCount >> 16) & 0xff);
+      SetCommandBuffer(&g_bufI2CSend, (g_PwrOnCount >>  8) & 0xff);
+      SetCommandBuffer(&g_bufI2CSend, (g_PwrOnCount >>  0) & 0xff);
+      break;

-    case COMMAND_SETGPIO2:
-      Serial.println("CMD:SETGPIO2_CNF");
-      ltmp = SetGPIOMode(6, pCmd->ucBuff[0] );
-      if ( ltmp >= 0 ) {
-        g_stSystemSetting.m_GPIO1mode = ltmp;
-      }
-      break;
-
-    case COMMAND_SETGPIO3:
-      Serial.println("CMD:SETGPIO3_CNF");
-      ltmp = SetGPIOMode(7, pCmd->ucBuff[0] );
-      if ( ltmp >= 0 ) {
-        g_stSystemSetting.m_GPIO1mode = ltmp;
-      }
-      break;
-
-    case COMMAND_SETGPIO4:
-      Serial.println("CMD:SETGPIO4_CNF");
-      ltmp = SetGPIOMode(8, pCmd->ucBuff[0] );
-      if ( ltmp >= 0 ) {
-        g_stSystemSetting.m_GPIO1mode = ltmp;
-      }
-      break;
-
-      break;
-
-    case COMMAND_SET_GPO1:
-    case COMMAND_SET_GPO2:
-    case COMMAND_SET_GPO3:
-    case COMMAND_SET_GPO4:
-      ctmp = pCmd->ucCmd - COMMAND_SET_GPO1;
-      Serial.print("CMD:SET_GPO_STATE"); Serial.println(ctmp);
-      if ( pCmd->ucBuff[0] == 0x00 ) {
-        digitalWrite( GPIO_PinMappping[ctmp], LOW );
-      } else {
-        digitalWrite( GPIO_PinMappping[ctmp], HIGH );
-      }
-      break;
-
-    case COMMAND_GET_GPI1:
-    case COMMAND_GET_GPI2:
-    case COMMAND_GET_GPI3:
-    case COMMAND_GET_GPI4:
-      ctmp = pCmd->ucCmd - COMMAND_SET_GPO1;
-      Serial.print("CMD:GET_GPI_STATE"); Serial.println(ctmp);
-      ltmp = digitalRead( GPIO_PinMappping[ctmp] );
-      SetCommandBuffer(&g_bufI2CSend, (unsigned char)ltmp );
-      break;
-
-    case COMMAND_GET_ADC1:
-    case COMMAND_GET_ADC2:
-    case COMMAND_GET_ADC3:
-    case COMMAND_GET_ADC4:
-      ctmp = pCmd->ucCmd - COMMAND_GET_ADC1;
-      Serial.print("CMD:GETADC_STATE"); Serial.println(ctmp);
-      ltmp = analogRead( ADC_PinMappping[ctmp] );
-      Serial.print("ADC:");
-      Serial.println(ltmp, HEX );
-      SetCommandBuffer(&g_bufI2CSend, (unsigned char)( (ltmp >> 8 ) & 0xff ));
-      SetCommandBuffer(&g_bufI2CSend, (unsigned char)(  ltmp & 0xff ));
-
-      break;
-
     default:
       break;
   }
-}
-
-
-// ---------------------------------------------------------------
-//    システム設定を行う
-//   ここは後でEEPROMから設定を行うようにする
-//   一番最初でEEPROM未設定か設定がおかしかったら初期化すること
-// ---------------------------------------------------------------
-void dumpEEPROM( void )
-{
-  Serial.println("--------");
-  for( int i=0; i<10; i++ ) {
-    Serial.println(EEPROM.read(i), HEX);
-  }
-}
-
-void initSystemSettingInfo( void )
-{
-  g_stSystemSetting.mEEPROMVersion = VERSION;
-  g_stSystemSetting.mAutoPowerOnMode = 0x01;
-  g_stSystemSetting.mIntervalTime = INTERVAL_TIME ;
-  g_stSystemSetting.m_GPIO1mode = INPUT_PULLUP;
-  g_stSystemSetting.m_GPIO2mode = INPUT;
-  g_stSystemSetting.m_GPIO3mode = INPUT;
-  g_stSystemSetting.m_GPIO4mode = INPUT;
-
-  g_stSystemSetting.m_bPowerStatus = false;
-  g_stSystemSetting.m_lRunTime = 0;
-  g_stSystemSetting.m_TimerCounter = 0;
-  g_stSystemSetting.m_WdtCounter = 0;
-
-  g_stSystemSetting.m_bPowerOffEventSignaled = false;
-  g_stSystemSetting.m_RTCEventSignaled = false;
-  g_stSystemSetting.m_PowerKeyEventSignaled = false;
-
-}
-
-void PutSystemSettings( void )
-{
-  unsigned long tmp;
-  Serial.print("VERSION:"); Serial.println(EEPROM.read(0), HEX );
-  Serial.print("AUTO-PW-ON:"); Serial.println(EEPROM.read(1), HEX );
-  Serial.print("GPIO1:"); Serial.println(EEPROM.read(6), HEX ); delay(10);
-  Serial.print("GPIO2:"); Serial.println(EEPROM.read(7), HEX ); delay(10);
-  Serial.print("GPIO3:"); Serial.println(EEPROM.read(8), HEX ); delay(10);
-  Serial.print("GPIO4:"); Serial.println(EEPROM.read(9), HEX ); delay(10);
-  tmp = EEPROM.read(2) & 0xff; tmp <<= 8;
-  tmp |= EEPROM.read(3) & 0xff; tmp <<= 8;
-  tmp |= EEPROM.read(4) & 0xff; tmp <<= 8;
-  tmp |= EEPROM.read(5) & 0xff;
-  Serial.print("INTERVAL:"); Serial.println( tmp ); delay(300);
-
-
-}
-void LoadSystemSettings( void )
-{
-  unsigned long tmp;
-  if ( EEPROM.read(0) == 0xFF ) {
-    Serial.println("EEPROM not defined.USe default."); delay(10);
-    initSystemSettingInfo();
-    SaveSystemSettings();
-    return;
-  }
-  g_stSystemSetting.mEEPROMVersion = EEPROM.read(0);
-  g_stSystemSetting.mAutoPowerOnMode = EEPROM.read(1);
-  if ( g_stSystemSetting.mAutoPowerOnMode != 0 && g_stSystemSetting.mAutoPowerOnMode != 1 ) {
-    Serial.println("Illigal value:AUTO-POWER-ON. Use default value."); delay(10);
-    g_stSystemSetting.mAutoPowerOnMode = 0x01;
-  }
-  tmp = EEPROM.read(2) & 0xff; tmp <<= 8;
-  tmp |= EEPROM.read(3) & 0xff; tmp <<= 8;
-  tmp |= EEPROM.read(4) & 0xff; tmp <<= 8;
-  tmp |= EEPROM.read(5) & 0xff;
-
-  g_stSystemSetting.mIntervalTime = tmp;
-
-  g_stSystemSetting.m_GPIO1mode = EEPROM.read(6);
-  g_stSystemSetting.m_GPIO2mode = EEPROM.read(7);
-  g_stSystemSetting.m_GPIO3mode = EEPROM.read(8);
-  g_stSystemSetting.m_GPIO4mode = EEPROM.read(9);
-
-}
-void SaveSystemSettings( void )
-{
-
-  EEPROM.write(0, VERSION);
-  EEPROM.write(1, (g_stSystemSetting.mAutoPowerOnMode == 0)?0:1);
-  EEPROM.write(2, (g_stSystemSetting.mIntervalTime >> 24 ) & 0xFF );
-  EEPROM.write(3, (g_stSystemSetting.mIntervalTime >> 16 ) & 0xFF );
-  EEPROM.write(4, (g_stSystemSetting.mIntervalTime >>  8 ) & 0xFF );
-  EEPROM.write(5, (g_stSystemSetting.mIntervalTime ) & 0xFF );
-  EEPROM.write(6, g_stSystemSetting.m_GPIO1mode & 0xff );
-  EEPROM.write(7, g_stSystemSetting.m_GPIO2mode & 0xff );
-  EEPROM.write(8, g_stSystemSetting.m_GPIO3mode & 0xff );
-  EEPROM.write(9, g_stSystemSetting.m_GPIO4mode & 0xff );
-
-}
-
-void ClearSystemSettings( void )
-{
-  initSystemSettingInfo();
-  SaveSystemSettings();
-}
-
-// ----------------------------------------------
-// 自動パワーON設定かをチェック
-bool isAutoPowerOn()
-{
-  return (g_stSystemSetting.mAutoPowerOnMode == 0x00 ) ? false:true;
-}
-
-// ----------------------------------------------
-// 寝ている時間がInterval Timer設定を経過したかをチェック
-bool  isTimerDone()
-{
-  if ( g_stSystemSetting.mIntervalTime == 0 ) return false;
-  if ( g_stSystemSetting.m_TimerCounter > g_stSystemSetting.mIntervalTime - 1) {
-    return true;
-  } else {
-    return false;
-  }
-}
-
-
-// ----------------------------------------------
-// Raspberry Pi側の電源がONしているかをチェック
-bool isRaspberryPiPowerOn()
-{
-  return g_stSystemSetting.m_bPowerStatus;
-}
-
-// ----------------------------------------------
-// RPiの電源ON/OFFを行う
-void setRaspberryPiPower( int nMode )
-{
-  if ( nMode  == RPI_POWER_ON ) {
-    digitalWrite( TSUBUTA_RPIPOWER, HIGH);
-    Serial.begin(UART_BAUDRATE);
-    Wire.begin(I2C_SLAVE_ADDRESS);
-    pinMode(SDA, INPUT);
-    pinMode(SCL, INPUT);
-
-    g_stSystemSetting.m_bPowerStatus = true;
-
-  } else {
-    digitalWrite( TSUBUTA_RPIPOWER, LOW);
-    g_stSystemSetting.m_bPowerStatus = false;
-  }
-}
-
-// ----------------------------------------------
-// GPIのチェックを行う
-void checkPowerOffFromMainCPU()
-{
-  if ( HIGH == digitalRead(  TSUBUTA_GPI_POFF ) ) {
-    g_stSystemSetting.m_bPowerOffEventSignaled = true;
-  }
-}
-void checkSystemInput(  )
-{
-
-  if ( LOW == digitalRead(  TSUBUTA_GPIO0 ) ) {
-    g_stSystemSetting.m_PowerKeyEventSignaled = true;
-  } else {
-    g_stSystemSetting.m_PowerKeyEventSignaled = false;
-  }
-}
-
-
-void setup() {
-
-  // シリアルポート初期化:
-  Serial.begin(UART_BAUDRATE);
-  Serial.println("Tsubuta add-on board.");
-
-  // Setup System
-  InitCommandBuffer(&g_bufI2CRecive);
-  InitCommandBuffer(&g_bufI2CSend);
-  ClearCommand((RCVCMD*)&g_RcvCmd);
-
-
-//  initSystemSettingInfo();
-  LoadSystemSettings();
-  PutSystemSettings();
-
-  // Set GPIO Settings
-  pinMode( TSUBUTA_RPIPOWER, OUTPUT );          // Raspberry Pi On/Off
-  pinMode( TSUBUTA_GPI_POFF, INPUT  );          // Interrupt signal from Raspberry Pi
-  pinMode( TSUBUTA_RPI_INT,  OUTPUT  );         // Interrupt signal to Raspberry Pi
-  pinMode( TSUBUTA_RTC_INT,  INPUT  );          // Interrupt signal from RTC
-
-  pinMode( TSUBUTA_GPIO0,  g_stSystemSetting.m_GPIO1mode  );
-  pinMode( TSUBUTA_GPIO1,  g_stSystemSetting.m_GPIO2mode  );
-  pinMode( TSUBUTA_GPIO2,  g_stSystemSetting.m_GPIO3mode  );
-  pinMode( TSUBUTA_GPIO3,  g_stSystemSetting.m_GPIO4mode  );
-
-  // GPIO Output setting
-  digitalWrite( TSUBUTA_RPIPOWER, LOW );
-  digitalWrite( TSUBUTA_RPI_INT, LOW );
-
-
-  // Set I2C
-  // TWIのライブラリの中で5Vにプルアップされてしまう。ここでPullUpをやめているけど、
-  // 瞬間的に５Vかかって壊れる可能性あるのでライブラリの中を修正したほうが良い。
-  // \hardware\arduino\avr\libraries\Wire\utility\twi.cの
-  // activate internal pullups for twi.
-  //  digitalWrite(SDA, 1);
-  //  digitalWrite(SCL, 1);
-  // の部分をコメントアウトしてプルアップ無効化すること
-  Wire.begin(I2C_SLAVE_ADDRESS);
-  pinMode(SDA, INPUT);
-  pinMode(SCL, INPUT);
-
-  Wire.onRequest( requestEvent );
-  Wire.onReceive( receiveEvent );
-
-  // Raspberry Pi Power On チェック
-  if ( isAutoPowerOn() == true ) {
-    Serial.println("Auto Power On.");
-    setRaspberryPiPower(RPI_POWER_ON);
-  } else {
-    Serial.println("Auto Power Off.");
-    setRaspberryPiPower(RPI_POWER_OFF);
-  }
-  delay(100);
-  setup_watchdog(4);  // Watch dog timer : 250msec
-  Serial.println("Initialize done.");
-
-}
-
-
-void SystemSleep()
-{
-
-  if (true == isRaspberryPiPowerOn()) return;
-
-  while( true ) {
-    system_sleep();
-    checkSystemInput();
-    if ( true == isTimerDone() ) {
-      setRaspberryPiPower(RPI_POWER_ON);
-      Serial.println(g_stSystemSetting.m_TimerCounter);
-      g_stSystemSetting.m_TimerCounter = 0;
-      Serial.println("Resume:Timer");
-      return;
-    }
-    if ( true == g_stSystemSetting.m_PowerKeyEventSignaled ) {
-      setRaspberryPiPower(RPI_POWER_ON);
-      g_stSystemSetting.m_PowerKeyEventSignaled = false;
-      Serial.println("Resume:Power Button");
-      return;
-    }
-  }
-}
-
-void SystemRun()
-{
-  while(true) {
-    checkPowerOffFromMainCPU();
-    if ( true == g_stSystemSetting.m_bPowerOffEventSignaled ) {
-      Serial.println("Power off from Raspberry Pi. 5sec wait...");
-      Serial.println("Enter to standby mode.");
-      Serial.println(g_stSystemSetting.m_TimerCounter);
-      delay(250);
-      setRaspberryPiPower(RPI_POWER_OFF);
-      g_stSystemSetting.m_bPowerOffEventSignaled = false;
-    }
-    return;
-  }
-}
-
-void loop() {
-  // put your main code here, to run repeatedly:
-#if 0
-  if ( IsCommandBufferEmpty(&g_bufI2CRecive) == false ) {
-
-  }
-#endif
-  if (true == isRaspberryPiPowerOn()) {
-    SystemRun();
-  } else {
-    SystemSleep();
-  }
-
 }

@@ -730,6 +245,11 @@
       if ( (g_RcvCmd.cParamLen = GetCmdParamLen(g_RcvCmd.ucCmd)) >= 0 ) {
         g_RcvCmd.cLen = 0;
       }
+      Serial.print("Command :");
+      Serial.println(g_RcvCmd.ucCmd,HEX);
+      Serial.print("Param Len :");
+      Serial.println(g_RcvCmd.cParamLen,HEX);
+
       if ( g_RcvCmd.cParamLen == 0x00 ) {
         Serial.println("Parse command");
         ParseCommand((RCVCMD *)&g_RcvCmd);
@@ -738,6 +258,8 @@
     } else {
       g_RcvCmd.ucBuff[g_RcvCmd.cLen] = c;
       g_RcvCmd.cLen++;
+      Serial.print("Rcv Len :");
+      Serial.println(g_RcvCmd.cLen,HEX);
       if ( g_RcvCmd.cLen >= g_RcvCmd.cParamLen ) {
         // パラメータがすべてそろったのでコマンド解析を行う
         Serial.println("Parse command");
@@ -755,11 +277,6 @@
   int len;

   Serial.println("I2C:Send Request ");
-
-//  if (true == GetCommandBuffer( &g_bufI2CSend, &c)) {
-//    Wire.write( c );
-//    Serial.println(c, HEX);
-//  }
   if ( g_bufI2CSend.len > 0 ) {
     if ( true == GetCommandBuffer( &g_bufI2CSend, buff, &len )) {
       Wire.write(buff, len );
@@ -767,6 +284,177 @@
   }
 }

+
+void PowerOn()
+{
+#if 0
+  Serial.println("P1");
+    delay(10);
+  for( int i=0; i<100; i++ ) {
+    digitalWrite( TSUBUTA_RPIPOWER, HIGH );
+    digitalWrite( TSUBUTA_RPIPOWER, LOW );
+    delay(20);
+  }
+
+  Serial.println("P2");
+    delay(10);
+  for( int i=0; i<100; i++ ) {
+    digitalWrite( TSUBUTA_RPIPOWER, HIGH );
+    digitalWrite( TSUBUTA_RPIPOWER, LOW );
+    delay(10);
+  }
+
+  Serial.println("P3");
+    delay(10);
+  for( int i=0; i<50; i++ ) {
+    digitalWrite( TSUBUTA_RPIPOWER, HIGH );
+    digitalWrite( TSUBUTA_RPIPOWER, LOW );
+    delay(5);
+  }
+
+  Serial.println("P4");
+    delay(10);
+  for( int i=0; i<50; i++ ) {
+    digitalWrite( TSUBUTA_RPIPOWER, HIGH );
+    digitalWrite( TSUBUTA_RPIPOWER, LOW );
+    delay(1);
+  }
+
+  Serial.println("P5");
+    delay(10);
+  for( int i=0; i<50; i++ ) {
+    digitalWrite( TSUBUTA_RPIPOWER, HIGH );
+    digitalWrite( TSUBUTA_RPIPOWER, LOW );
+  }
+
+#endif
+
+  Serial.println("P6");
+  delay(10);
+  digitalWrite( TSUBUTA_RPIPOWER, HIGH );
+  g_bPowerOn = true;
+}
+
+// ----------------------------------------------
+
+void setup() {
+  // put your setup code here, to run once:
+  // シリアルポート初期化:
+  Serial.begin(115200);
+  Serial.println("Tsubuta add-on board.");
+  Serial.println(MCUSR,HEX);
+
+  Serial.println("Initialize GPIO.");
+  pinMode( TSUBUTA_RPIPOWER, OUTPUT );          // Raspberry Pi On/Off
+  pinMode( TSUBUTA_GPI_POFF, INPUT  );          // Interrupt signal from Raspberry Pi
+  pinMode( 10, OUTPUT );                        // BOOTMODE
+  pinMode( 9, OUTPUT );                         // BATTERY ALERT(to RPi)
+  digitalWrite( TSUBUTA_RPIPOWER, LOW );
+  digitalWrite( 9, LOW );
+
+#if 1
+  // Set I2C
+  // TWIのライブラリの中で5Vにプルアップされてしまう。ここでPullUpをやめているけど、
+  // 瞬間的に５Vかかって壊れる可能性あるのでライブラリの中を修正したほうが良い。
+  // \hardware\arduino\avr\libraries\Wire\utility\twi.cの
+  // activate internal pullups for twi.
+  //  digitalWrite(SDA, 1);
+  //  digitalWrite(SCL, 1);
+  // の部分をコメントアウトしてプルアップ無効化すること
+  Serial.println("Initialize I2C.");
+  Wire.begin(I2C_SLAVE_ADDRESS);
+  pinMode(SDA, INPUT);
+  pinMode(SCL, INPUT);
+
+  Wire.onRequest( requestEvent );
+  Wire.onReceive( receiveEvent );
+#endif
+
+  // Setup System
+  Serial.println("Buffer initialize.");
+  InitCommandBuffer(&g_bufI2CRecive);
+  InitCommandBuffer(&g_bufI2CSend);
+  ClearCommand((RCVCMD*)&g_RcvCmd);
+
+  Serial.println("Get Bootmode.");
+#if 1
+  digitalWrite( 10, HIGH );
+  delay(100);
+  int v=0;
+  v = analogRead(A7);
+  digitalWrite( 10, LOW );
+  Serial.println(v);
+
+  // 817    BOOTMODE4
+  // 765    BOOTMODE3
+  // 680    BOOTMODE2
+
+  // 509    BOOTMODE1
+  // 0      BOOTMODE0
+
+  if ( v < 500 ) {
+//    g_IntervalTime = 900;     // BOOTMODE0 - 15min
+//    g_IntervalTime = 844;     // BOOTMODE0 - 15min
+    g_IntervalTime = 563;     // BOOTMODE0 - 10min
+  }
+  else if ( v >= 500 && v < 600 ) {
+//    g_IntervalTime = 1687;     // BOOTMODE1 - 30min 1800sec
+    g_IntervalTime = 1125;     // BOOTMODE1 - 30min 1800sec
+  }
+  else if ( v >= 600 && v < 720 ) {
+    g_IntervalTime = 3375; // 3600;     // BOOTMODE2 - 1h
+  }
+  else if ( v >= 720 && v < 790 ) {
+    g_IntervalTime = 3375 * 12 ; //3600 * 12;     // BOOTMODE3 - 12h
+  }
+  else if ( v >= 790  ) {
+    g_IntervalTime = 3375 * 24;     // BOOTMODE3 - 24h
+  }
+#else
+  g_IntervalTime = 563;     // BOOTMODE0 - 10min
+#endif
+
+  g_WdtCounter = 0;
+  g_lRunTime = 0;
+  g_TimerCounter = 1;
+  g_PwrOnCount = 1;
+  setup_watchdog(6);    // 250msec timer
+
+  // GPIO Output setting
+  Serial.println("RPI P.ON.");
+  delay(100);
+  PowerOn();
+
+}
+
+void loop() {
+  // put your main code here, to run repeatedly:
+
+  if ( g_bPowerOn == true ) {
+    Serial.print("Runtime :");
+    Serial.println(g_lRunTime);
+    if ( g_lRunTime > BATTERY_ALERT_THREAD ) {
+      Serial.println("Battery down");
+      digitalWrite( 9, HIGH );
+    }
+    int n = digitalRead(  TSUBUTA_GPI_POFF );
+    if ( n == HIGH ) {
+      digitalWrite( 9, LOW );
+      digitalWrite( TSUBUTA_RPIPOWER, LOW );
+      g_bPowerOn = false;
+    }
+    delay(500);
+  } else {
+    system_sleep();
+
+    if ( g_TimerCounter == 0 ) {
+      Serial.begin(115200);
+      Serial.println("Resume.");
+      PowerOn();
+      g_PwrOnCount++;
+    }
+  }
+}

 // --------------------------------
 //   for Standby mode Function
@@ -776,9 +464,11 @@
 void system_sleep() {                   // システム停止
   cbi(ADCSRA,ADEN);                     // ADC 回路電源をOFF (ADC使って無くても120μA消費するため）
   set_sleep_mode(SLEEP_MODE_PWR_DOWN);  // パワーダウンモード
+//  set_sleep_mode(SLEEP_MODE_PWR_SAVE);  // パワーダウンモード
   sleep_enable();
   sleep_mode();                         // ここでスリープに入る
   sleep_disable();                      // WDTがタイムアップしたらここから動作再開
+  wdt_reset();
   sbi(ADCSRA,ADEN);                     // ADC ON
 }  //system_sleep

@@ -801,36 +491,17 @@
   WDTCSR |= _BV(WDIE);
 }  //setup_watchdog

-void setPowDownMode(){                  // CPUをパワーダウンモードに設定
-  // CPU Sleep Modes          参考にしたプログラムに入っていたがこのルーチンは使用しない
-  // SM2 SM1 SM0 Sleep Mode
-  // 0    0  0 Idle
-  // 0    0  1 ADC Noise Reduction
-  // 0    1  0 Power-down
-  // 0    1  1 Power-save
-  // 1    0  0 Reserved
-  // 1    0  1 Reserved
-  // 1    1  0 Standby(1)
-
-  // パワーダウンモードへ設定
-  cbi( SMCR,SE );      // sleep enable, power down mode
-  cbi( SMCR,SM0 );     // power down mode
-  sbi( SMCR,SM1 );     // power down mode
-  cbi( SMCR,SM2 );     // power down mode
-}  //  setPowDownMode
-
 ISR(WDT_vect) {                         // WDTがタイムアップした時に実行される処理
-  g_stSystemSetting.m_WdtCounter++;
-  if ( 0 == ( g_stSystemSetting.m_WdtCounter % 4 )) {
-    g_stSystemSetting.m_lRunTime++;           // 連続通電時間は１秒ごとにカウント
-    g_stSystemSetting.m_TimerCounter++;
-    g_stSystemSetting.m_TimerCounter %= ( g_stSystemSetting.mIntervalTime + 1);
-  }
-}
-
-
-
-
-
-
-
+  g_WdtCounter++;
+//  if ( 0 == ( g_WdtCounter % 4 )) {
+    if ( g_bPowerOn == true ) {
+      g_lRunTime++;           // 連続通電時間は１秒ごとにカウント
+    }
+    g_TimerCounter++;
+    g_TimerCounter %= g_IntervalTime;
+//  }
+}
+
+
+
+


display content fixed

display content fixed


AD7173-8.ino fixed adc_data_mode

AD7173-8.ino fixed adc_data_mode

--- AD7173-8.ino
+++ AD7173-8.ino
@@ -122,7 +122,7 @@
 #define DATA_READY digitalRead(MISO) == LOW

 /* enable/disable debug */
-#define DEBUG_ENABLED 1
+#define DEBUG_ENABLED 1+

 /* default adc data conversion mode */
 int adc_data_mode = CONTINUOUS_CONVERSION_MODE;
@@ -307,7 +307,7 @@
     /* when continuous read mode */
     if (mode == CONTINUOUS_READ_MODE) {
         /* set the adc to continuous read mode, the data register can be read directly when DATA_READY */
-        if_mode_value[1] |= 0x08;
+        if_mode_value[1] |= 0x80;
         /* enable continuouse conversion mode */
         adc_mode_value[1] &= 0x8F;
     /* when single conversion mode */


Functional clapMeter

Functional clapMeter

--- sketches/clapMeter/clapMeter.ino
+++ sketches/clapMeter/clapMeter.ino
@@ -18,7 +18,7 @@

 #define SOUND_SENSOR A0
 #define SOUND_SENSOR_2 A2
-#define THRESHOLD_FAIL 200 //The threshold to turn the led on 400.00*5/1024 = 1.95v
+#define THRESHOLD_FAIL 400 //The threshold to turn the led on 400.00*5/1024 = 1.95v
 #define THRESHOLD_GOOD 400
 #define THRESHOLD_WIN 600

@@ -38,12 +38,12 @@
 byte *hz;
 byte *wordresult;
 int sensorValue;
-int average;
 int counter = 0;
-boolean clapMeterOn = false;
 double clapMeter = 0;
 int sensor = 0;
 int sensor_2 = 0;
+int goodClap = 0;
+int badClap = 0;
 int result = 0;
 boolean scanning = true;
 SoftwareSerial lcd(99, LCD_OUT);
@@ -77,11 +77,8 @@

 void loop()
 {
-
     if(scanning){
-        scanning = false;
-        //result = scanClaps();
-        result = 700;
+        result = scanClaps();
     }else{
         showResult();
     }
@@ -93,7 +90,7 @@
         Serial.println("WIN");
     } else if (result >= THRESHOLD_GOOD){
         wordresult = good;
-        Serial.println("GOOD");
+        Serial.println("GOOD");
     } else {
         wordresult = fail;
         Serial.println("FAIL");
@@ -114,12 +111,34 @@
 }

 int scanClaps(){
-    sensor = analogRead(SOUND_SENSOR);
-    sensor_2 = analogRead(SOUND_SENSOR_2);
-
-    if(min(sensor,sensor_2) > 0)
-    {
-        sensorValue = max(sensor, sensor_2);
+    boolean keep = true;
+    while(keep){
+        sensor = analogRead(SOUND_SENSOR);
+        sensor_2 = analogRead(SOUND_SENSOR_2);
+        if(min(sensor,sensor_2) > 0){
+            sensorValue = max(sensor, sensor_2);
+            if(sensorValue > THRESHOLD_FAIL){
+                clapMeter = clapMeter + sensorValue;
+                goodClap++;
+            } else {
+                if(badClap<100){
+                    badClap++;
+                } else {
+                    keep = false;
+                }
+            }
+
+        }
+    }
+
+    result = clapMeter/goodClap;
+    goodClap = 0;
+    badClap = 0;
+    scanning = false;
+
+    return result;
+}
+
         /*
         setHistogram(sensorValue);

@@ -138,28 +157,6 @@
         }
         */

-        if(sensorValue > THRESHOLD_FAIL)
-        {
-            clapMeterOn = true;
-            clapMeter = clapMeter + sensorValue;
-            counter++;
-        }
-   }
-   if (clapMeterOn == true && sensorValue < 50)
-   {
-        average = clapMeter/counter;
-        Serial.println("FIN DEL CONTEO");
-        Serial.println(average);
-        clapMeterOn = false;
-        //show_results
-
-        counter = 0;
-        clapMeter = 0;
-    }
-
-    scanning = false;
-
-}

 void lcd_init()
 {


Update MDriver_no_PWM.ino

Update MDriver_no_PWM.ino

--- examples/MDriver_no_PWM/MDriver_no_PWM.ino
+++ examples/MDriver_no_PWM/MDriver_no_PWM.ino
@@ -18,12 +18,13 @@

 /*
  * Библиотека содержит следующие функции:
- * speed(uint8_t speed); - принимает значение от 0 до 255, управляет
+ * speed(uint8_t speed); - принимает значение от 0 до 255, также принимает
+ *  константу MAX, что соответствует значению 255. Управляет
  *  скоростью вращения. Если двигатель инициализирован без регулировки
  *  скорости, то эта функция становится неактивной.
- * forward(); и backward(); - управляют вращением двигателе в разных
+ * forward(); и backward(); - управляют вращением двигателя в разных
  *  направлениях
- * stop(); - остановка двигателей
+ * stop(); - остановка двигателя
  */

 //Подключение двигателей без регулировки скорости,


[fix] implement correct message bound parsing

--- src/du.ino
+++ src/du.ino
@@ -12,8 +12,9 @@
 void loop() {
   while(Serial.available() > 0) {
     char x = Serial.read();
-    if (x != '\n' && x != '\r') messageBuffer[index++] = x;
-    if (index == 6) process();
+    if (x == '!') index = 0;      // start
+    else if (x == '.') process(); // end
+    else messageBuffer[index++] = x;
   }
 }

@@ -37,7 +38,7 @@
   } else if (strcmp(cmd, "02") == 0) {
       dr(pin, val);
   } else {
-    Serial.println(-1);
+    Serial.println(messageBuffer);
   }
 }

@@ -62,7 +63,5 @@
 /*
  * Digital read
  */
-void dr(char *pin, char *val) {
-  Serial.println('2');
-}
+void dr(char *pin, char *val) {}


Only write to serial from within 'loop'. Debugging disabled.

--- src/du.ino
+++ src/du.ino
@@ -41,7 +41,7 @@

 /*
- * Deal with a full message and determine function to call
+ * Deal with a full request and determine function to call
  */
 void process() {
   strncpy(cmd, request, 2);
@@ -61,7 +61,7 @@
     aux[4] = '\0';
   }

-  if (debug) Serial.println(request);
+  // if (debug) Serial.println(request);
   int cmdid = atoi(cmd);

   switch(cmdid) {
@@ -139,12 +139,9 @@
  * fire, read
  */
 void handlePing(char *pin, char *val, char *aux) {
-  if (debug) Serial.println("ss");
-  int p = getPin(pin);
-
-  if(p == -1) { if(debug) Serial.println("badpin"); return; }
-  Serial.println("got signal");
-
+  int p = getPin(pin);
+  if (p == -1) return;
+
   // 01(1) Fire and Read
   if (atoi(val) == 1) {
     char m[16];
@@ -156,11 +153,11 @@
     delayMicroseconds(5);
     digitalWrite(p, LOW);

-    Serial.println("ping fired");
+    // Serial.println("ping fired");

     pinMode(p, INPUT);
     sprintf(m, "%s::read::%08d", pin, pulseIn(p, HIGH));
-    Serial.println(m);
+    response = m;

     delay(50);
   }
@@ -173,17 +170,15 @@
  * attach, detach, write, read, writeMicroseconds, attached
  */
 void handleServo(char *pin, char *val, char *aux) {
-  if (debug) Serial.println("ss");
-  int p = getPin(pin);
-  if(p == -1) { if(debug) Serial.println("badpin"); return; }
-  Serial.println("signal: servo");
-
+  int p = getPin(pin);
+  if (p == -1) return;
+
   // 00(0) Detach
   if (atoi(val) == 0) {
     servo.detach();
     char m[12];
     sprintf(m, "%s::detached", pin);
-    Serial.println(m);
+    response = m;

   // 01(1) Attach
   } else if (atoi(val) == 1) {
@@ -191,28 +186,20 @@
     servo.attach(p);
     char m[12];
     sprintf(m, "%s::attached", pin);
-    Serial.println(m);
+    response = m;

   // 02(2) Write
   } else if (atoi(val) == 2) {
-    Serial.println("writing to servo");
-    Serial.println(atoi(aux));
     // Write to servo
     servo.write(atoi(aux));
     delay(15);

-    // TODO: Experiment with microsecond pulses
-    // digitalWrite(pin, HIGH);   // start the pulse
-    // delayMicroseconds(pulseWidth);  // pulse width
-    // digitalWrite(pin, LOW);    // stop the pulse
-
   // 03(3) Read
   } else if (atoi(val) == 3) {
-    Serial.println("reading servo");
     int sval = servo.read();
     char m[13];
     sprintf(m, "%s::read::%03d", pin, sval);
-    Serial.println(m);
+    response = m;
   }
 }

@@ -224,10 +211,10 @@
 void toggleDebug(char *val) {
   if (atoi(val) == 0) {
     debug = false;
-    Serial.println("goodbye");
+    response = "goodbye";
   } else {
     debug = true;
-    Serial.println("hello");
+    response = "hello";
   }
 }


Update esp.ino

Update esp.ino

Fixed esp code, for some reason i forgot a return statement.

--- esp12/esp/esp.ino
+++ esp12/esp/esp.ino
@@ -56,18 +56,22 @@
 			if (checkIfStartedTrip() == true)
 			sendInfo();
 		}
+		delay(1000);
 	}
 }

 boolean checkIfStartedTrip() {
-	char path[50] = "/api/v1/devices/currentTrip/";
-	strncpy(path, serialNo, 6);
+	char path[100] = "/api/v1/devices/currentTrip/";
+	strcat(path, serialNo);
 	HTTPClient http;
 	http.begin(path);
 	http.sendRequest("GET");
 	String payload = http.getString();
 	Serial.println(payload);
-	delay(1000);
+	if (payload == "true") {
+		return true;
+	}
+	return false;
 }


Update BB-UNIT.ino

Update BB-UNIT.ino

--- Firmware/BB-UNIT/BB-UNIT.ino
+++ Firmware/BB-UNIT/BB-UNIT.ino
@@ -342,7 +342,7 @@
     if (remote.available()) // IF RF24 ---> radio.available()
     {
     	char msg[64] = {0};
-    	radio.readBytesUntil('\n', msg, sizeof msg);
+    	remote.readBytesUntil('\n', msg, sizeof msg); // IF RF24 ---> radio.read(&msg, sizeof(msg));
     	newData = true;
     }

@@ -361,7 +361,7 @@
        		int val = atoi(p + 1);
        		switch (*p)
        		{
-		    case 'x': setpointX  = val; break;
+		        case 'x': setpointX  = val; break;
           	    case 'y': setpointY  = val; break;
       	  	    case 'm': multiplier = val; break;
       		    case 'i': invertXY   = val; break;


Updates xadow-watch to use button API

Updates xadow-watch to use button API

--- xadow-watch.ino
+++ xadow-watch.ino
@@ -58,13 +58,18 @@
   animation_boot();
   oled.fillScreen(COLOR_BLACK);

+  button_init();
+
   buzzer_init();
   buzzer_jingle(0);

   menu_init();
   status_init();
   watch_init(now);
-  batlog_init(0x01);
+
+  // log battery once every 5 minutes, giving us >80 hr battery log
+  batlog_init(0x00, 5);
+
   sync_init();

   oled.fillScreen(COLOR_BLACK);
@@ -73,13 +78,14 @@

   oled.drawString("Disconnect USB", 0, 0, FONT_SIZE, COLOR_RED);
   oled.drawString("then press WAKE", 0, LINE_HEIGHT, FONT_SIZE, COLOR_RED);
-  while(digitalRead(10) == HIGH);;
+
+  button_wait(BUTTON_WAKE);
+  buzzer_sound(BUZZER_SOUND_CHIME);

   mcu_reduce_features();

   now = 0;
   checkpoint = millis();
-
 }

 void loop() {
@@ -106,11 +112,14 @@
   power_spi_enable();
   uint8_t changes = watch_tick(now);

+  if (changes >= 3) buzzer_sound(BUZZER_SOUND_CHIME);
+
   batlog_tick(changes);

   Screen nextscreen = currentScreen;

-  if (digitalRead(10) == LOW) {
+  if (button_pressed(BUTTON_WAKE)) {
+    buzzer_sound(BUZZER_SOUND_BUTTON);
     nextscreen = SCREEN_STATUS;
   } else {
     nextscreen = SCREEN_WATCH;


Moved the LED pins to PWM pins so that I could dim them to roughly the same setting as the matrix display.  This keeps them from being too bright at night.

--- SunriseAlarm.ino
+++ SunriseAlarm.ino
@@ -175,12 +175,13 @@
 #define ENCODER_PIN1 12

-const int AlarmButton = 7;
-const int AlarmLED = 8;
-const int TimeButton = 9;
-const int TimeLED = 13;
-const int OffButton = A0;
-const int AlarmEnabledSwitch = 5;
+#define AlarmButton 7
+#define AlarmLED 5
+#define TimeButton 9
+#define TimeLED 10
+#define OffButton A0
+#define AlarmEnabledSwitch 8
+#define RotaryButton A1

 #define NUM_LED 32
 #define LED_PIN 6
@@ -547,6 +548,7 @@
   pinMode(AlarmButton,INPUT_PULLUP);
   pinMode(TimeButton,INPUT_PULLUP);
   pinMode(AlarmEnabledSwitch, INPUT_PULLUP);
+  pinMode(RotaryButton, INPUT_PULLUP);
   pinMode(OffButton,INPUT);
   pinMode(AlarmLED, OUTPUT);
   pinMode(TimeLED, OUTPUT);
@@ -557,9 +559,9 @@
   Timer1.attachInterrupt(timerIsr);
   //timer.initialize(timerPeriod);
   //timer.pwm(LEDpinA, 0); //set up pin 9
+  while (!eeprom.isPresent()) { delay(1); }
   matrix.begin(0x70);
   display_todd();
-  //while (!eeprom.isPresent()) { delay(1); }
   readBrightnessFromEEPROM();
   matrix.setBrightness(matrixBrightness); // 0-15
   readSunDownDeltaFromEEPROM();
@@ -637,7 +639,7 @@

 void setTime() {
-  digitalWrite(TimeLED,HIGH);
+  analogWrite(TimeLED,matrixBrightness*255/16+15);
   DateTime currentTime = RTC.now();
   ClockTime t(currentTime);
   display_Cloc();
@@ -678,7 +680,7 @@
 }

 void setAlarm() {
-  digitalWrite(AlarmLED,HIGH);
+  analogWrite(AlarmLED,matrixBrightness*255/16+1);
   display_ALAr();
   delay(1000);
   updateTimeDisplay(alarmTime,true,true);


added stopwatch to the menu

added stopwatch to the menu

--- TrinketWatch.ino
+++ TrinketWatch.ino
@@ -1,17 +1,9 @@
 /*********************************************************************
- * This is an example for our Monochrome OLEDs based on SSD1306 drivers
  *
- * Pick one up today in the adafruit shop!
- * ------> http://www.adafruit.com/category/63_98
+ * All functions defined here written by and (c) Davis Haupt under the MIT License.
  *
- * This example is for a 128x64 size display using I2C to communicate
- * 3 pins are required to interface (2 I2C and one reset)
- *
- * Adafruit invests time and resources providing this open source code,
- * please support Adafruit and open-source hardware by purchasing
- * products from Adafruit!
- *
- * Written by Limor Fried/Ladyada  for Adafruit Industries.
+ *
+ * Graphics and Display Library Written by Limor Fried/Ladyada  for Adafruit Industries.
  * BSD license, check license.txt for more information
  * All text above, and the splash screen must be included in any redistribution
  *********************************************************************/
@@ -28,18 +20,9 @@
 #error("Height incorrect, please fix Adafruit_SSD1306.h!");
 #endif

-
-
-// Button Variables
-
 int bpins[] = {8, 9, 10};// pin 2 isn't exposed on the trinket, just a placeholder.
 int buttons[] = {0, 0, 0};
-int lastButtonStates[] = {0, 0, 0};
-long lastDebounceTimes[] = {0, 0, 0};
-long debounceDelay = 50;
-
 long last = millis();
-int lastReadings[] = {0,0,0};

 void setup() {

@@ -66,7 +49,7 @@

 void loop() {
   if (pressedOnce(1)) {
-    mnu = (mnu + 1) % 2;
+    mnu = (mnu + 1) % 3;
   }
   if (mnu == 0) {
     if (pressedOnce(0)) {
@@ -87,61 +70,10 @@
   else if (mnu == 1) {
     display.clearDisplay();
     pong();
-  }
-}
-
-void menu() {
-  boolean b = true;
-  display.setTextSize(1);
-  int m = 0;
-  while (b) {
+  } else if (mnu == 2) {
     display.clearDisplay();
-    display.setCursor(0, 0);
-    display.println("Time\nPong");
-    if (pressedOnce(0))
-      m = abs(m-1) % 2;
-    else if (pressedOnce(2))
-      m = abs(m+1) % 2;
-    else if (pressedOnce(1))
-      Serial.println(m);
-
-
-    if (m == 0) {
-      display.setCursor(30, 0);
-    }
-    else {
-      display.setCursor(30, 10);
-    }
-    display.println("*");
-    display.display();
+    stopwatch();
   }
 }

-void updateButtonStates() {
-  for (int i = 0; i < 3; ++i) {
-    int reading = digitalRead(bpins[i]);
-    if (reading != lastButtonStates[i]) {
-      lastDebounceTimes[i] = millis();
-    }
-    if ((millis() - lastDebounceTimes[i]) > debounceDelay) {
-      if (reading == LOW) {
-       buttons[i] = 1;
-      } else {
-       buttons[i] = 0;
-      }
-    }
-    lastButtonStates[i] = reading;
-  }
-}
-
-boolean pressedOnce(int b) {
-  updateButtonStates();
-  boolean r;
-  if (buttons[b] != lastReadings[b] && buttons[b])
-    r = true;
-  else
-    r = false;
-  lastReadings[b] = buttons[b];
-  return r;
-}


[major] add handleServo function, expand messageBuffer

--- src/du.ino
+++ src/du.ino
@@ -1,10 +1,13 @@
+#include <Servo.h>

-char messageBuffer[6];
+char messageBuffer[11];
 int index = 0;
 char cmd[3];
 char pin[3];
 char val[3];
+char aux[4];
 bool debug = false;
+Servo servo;

 void setup() {
   Serial.begin(115200);
@@ -31,6 +34,8 @@
   pin[2] = '\0';
   strncpy(val, messageBuffer + 4, 2);
   val[2] = '\0';
+  strncpy(aux, messageBuffer + 6, 3);
+  aux[2] = '\0';

   if (debug) {
     Serial.println(messageBuffer);
@@ -39,9 +44,11 @@
   if (strcmp(cmd, "00") == 0) {
       sm(pin, val);
   } else if (strcmp(cmd, "01") == 0) {
-      dw(pin, val);
+      dw(pin, val); // digital write
   } else if (strcmp(cmd, "02") == 0) {
-      dr(pin, val);
+      dr(pin, val); //  digital read
+  } else if (strcmp(cmd, "98") == 0) {
+      handleServo(pin, val, aux);
   } else if (strcmp(cmd, "99") == 0) {
       toggleDebug(val);
   }
@@ -104,3 +111,22 @@
   Serial.println(m);
 }

+/*
+ * Handle Servo commands
+ * attach, detach, write, read, writeMicroseconds, attached
+ */
+void handleServo(char *pin, char *val, char *aux) {
+  if (debug) Serial.println("ss");
+  int p = atoi(pin);
+  Serial.println("got signal");
+  if (strcmp(val, "00") == 0) {
+    servo.detach();
+  } else if (strcmp(val, "01") == 0) {
+    servo.attach(p);
+    Serial.println("attached");
+  } else if (strcmp(val, "02") == 0) {
+    Serial.println("writing to servo");
+    Serial.println(atoi(aux));
+    servo.write(atoi(aux));
+  }
+}


[fix] set pinMode on every digitalWrite

[fix] set pinMode on every digitalWrite

--- src/du.ino
+++ src/du.ino
@@ -56,6 +56,7 @@
  */
 void dw(char *pin, char *val) {
   int p = atoi(pin);
+  pinMode(p, OUTPUT);
   if (strcmp(val, "00") == 0) digitalWrite(p, LOW);
   else digitalWrite(p, HIGH);
 }


Add SmartMatrixShieldV4.h header

Add SmartMatrixShieldV4.h header

--- AnimatedGIFs.ino
+++ AnimatedGIFs.ino
@@ -65,6 +65,7 @@
  */

 #if defined (ARDUINO)
+//#include <SmartMatrixShieldV4.h>  // uncomment this line for SmartMatrix Shield V4 (needs to be before #include <SmartMatrix3.h>)
 #include <SmartMatrix3.h>
 #elif defined (SPARK)
 #include "application.h"


added line sensors and misc

added line sensors and misc

--- h_sumo_search.ino
+++ h_sumo_search.ino
@@ -21,31 +21,30 @@
 int BIN1 = 12; //Direction
 int BIN2 = 11; //Direction

+//HC-SR04
 #define leftEcho 2  // left Echo Pin
 #define leftTrig 4  // left Trigger Pin
 #define rightEcho 7 // right Echo Pin
 #define rightTrig 6 // right Trigger Pin

-// POSSIBLY CHANGE THIS FOR ARENA SIZE
-int maximumRange = 150; // Maximum range needed
-int minimumRange = 1; // Minimum range needed
+// Distance variables and parameters
+#define maximumRange 20 // Maximum range needed
+#define minimumRange 1  // Minimum range needed
 long leftDistance = 1000;
 long rightDistance = 1000;
-long prevLeft;
-long prevRight;
+long prevLeft, prevRight;
 long durationLeft, cmLeft, inchesLeft, cmRight, inchesRight, durationRight;
-long lD[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
-long rD[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
-int iterator = 0;
-
+
+//search()
 boolean found = false;  // used for search()
-boolean lost = false;
-
-boolean tagged = false; // used for follow()
+boolean lost = false;   // true after enemy is found for first time
+
+//follow()
+boolean tagged = false;
 int rightDirMod = 0;
 int leftDirMod = 0;

-//------------------------------
+//speed variables and parameters
 #define baseSpeed 128
 int leftMod = 0;
 int rightMod = 0;
@@ -58,7 +57,20 @@

 int leftDir = 0;
 int rightDir = 1;
-//-----------------------------
+
+//line sensor pins(temporarily RPR-220)
+#define frontInput  A0
+#define frontLed    13
+#define leftInput   A1
+#define leftLed     17
+#define rightInput  A2
+#define rightLed    18
+
+//line sensor variables and parameters
+#define lineThreshold 100
+boolean initialize = true;
+long frontBaseVal, leftBaseVal, rightBaseVal;
+long frontVal, leftVal, rightVal;

 void setup(){
   Serial.begin (9600);
@@ -77,11 +89,111 @@
   pinMode(rightTrig, OUTPUT);
   pinMode(rightEcho, INPUT);

-  //search();
+  pinMode(frontInput, INPUT);
+  pinMode(leftInput, INPUT);
+  pinMode(rightInput, INPUT);
+  pinMode(frontLed, OUTPUT);
+  pinMode(leftLed, OUTPUT);
+  pinMode(rightLed, OUTPUT);
+
+  readLine();
 }

 void loop(){
   search();
+}
+
+//line sensors take calibration reading
+void readLine() {
+ int ambient = 0;
+ int lit = 0;
+ int value = 0;
+
+ digitalWrite(frontLed, LOW);
+ delay(5);                            //To give ADC and LED transition time
+ ambient = analogRead(frontInput);
+ digitalWrite(frontLed, HIGH);
+ delay(5);
+ lit = analogRead(frontInput);
+ if(initialize) {
+  frontBaseVal = lit - ambient;
+ }
+ frontVal = lit - ambient;
+
+ digitalWrite(leftLed, LOW);
+ delay(5);                            //To give ADC and LED transition time
+ ambient = analogRead(leftInput);
+ digitalWrite(leftLed, HIGH);
+ delay(5);
+ lit = analogRead(leftInput);
+ if(initialize) {
+  leftBaseVal = lit - ambient;
+ }
+ leftVal = lit - ambient;
+
+ digitalWrite(rightLed, LOW);
+ delay(5);                            //To give ADC and LED transition time
+ ambient = analogRead(rightInput);
+ digitalWrite(rightLed, HIGH);
+ delay(5);
+ lit = analogRead(rightInput);
+ if(initialize) {
+  rightBaseVal = lit - ambient;
+ }
+ rightVal = lit - ambient;
+ if(!initialize) {
+  checkLine();
+ } else {
+  initialize = false;
+  Serial.println("initialization done.");
+ }
+}
+
+void checkLine() {
+  if((frontVal - frontBaseVal) >= lineThreshold) {
+    recovery(1);
+    return;
+  }
+  if((leftVal - leftBaseVal) >= lineThreshold) {
+    recovery(2);
+    return;
+  }
+  if((rightVal - rightBaseVal) >= lineThreshold) {
+    recovery(3);
+    return;
+  }
+}
+
+void recovery(int sensor) {
+  // 0 is forward, 1 is backward
+  //move(1, 200, rightDir); //right motor
+  //move(2, 200, leftDir); //left motor
+  switch(sensor) {
+    case 1:   //front, burst of back up
+      Serial.println("FRONT TRIGGERED");
+      move(1, 255, 1);
+      move(2, 255, 1);
+      delay(1000);
+      break;  //left, burst forward, back up to right
+    case 2:
+      Serial.println("LEFT TRIGGERED");
+      move(1, 255, 0);
+      move(2, 255, 0);
+      delay(500);
+      move(1, 128, 1);
+      move(2, 255, 1);
+      delay(500);
+      break;
+    case 3:   //right, burst forward, back up to left
+      Serial.println("RIGHT TRIGGERED");
+      move(1, 255, 1);
+      move(2, 255, 1);
+      delay(500);
+      move(2, 128, 1);
+      move(1, 255, 1);
+      delay(500);
+      break;
+  }
 }

 void move(int motor, int speed, int direction){
@@ -89,26 +201,25 @@
 //motor: 0 for B 1 for A
 //speed: 0 is off, and 255 is full speed
 //direction: 0 clockwise, 1 counter-clockwise
-
-  digitalWrite(STBY, HIGH); //disable standby
-
-  boolean inPin1 = LOW;
-  boolean inPin2 = HIGH;
-
-  if(direction == 1){
-    inPin1 = HIGH;
-    inPin2 = LOW;
-  }
-
-  if(motor == 1){
-    digitalWrite(AIN1, inPin1);
-    digitalWrite(AIN2, inPin2);
-    analogWrite(PWMA, speed);
-  }else{
-    digitalWrite(BIN1, inPin1);
-    digitalWrite(BIN2, inPin2);
-    analogWrite(PWMB, speed);
-  }
+ digitalWrite(STBY, HIGH); //disable standby
+
+ boolean inPin1 = LOW;
+ boolean inPin2 = HIGH;
+
+ if(direction == 1){
+   inPin1 = HIGH;
+   inPin2 = LOW;
+ }
+
+ if(motor == 1){
+   digitalWrite(AIN1, inPin1);
+   digitalWrite(AIN2, inPin2);
+   analogWrite(PWMA, speed);
+ }else{
+   digitalWrite(BIN1, inPin1);
+   digitalWrite(BIN2, inPin2);
+   analogWrite(PWMB, speed);
+ }
 }

 void stop(){
@@ -117,67 +228,33 @@
 }

 void calcDistance() {
-  if (iterator == 20) {
-    iterator = 0;
-  }
-  prevLeft = leftDistance;
-  prevRight = rightDistance;
-/* The following trigPin/echoPin cycle is used to determine the
- distance of the nearest object by bouncing soundwaves off of it. */
-// digitalWrite(leftTrig, LOW);
-// delayMicroseconds(2);
-// digitalWrite(leftTrig, HIGH);
-// delayMicroseconds(10);
-// digitalWrite(leftTrig, LOW);
-// duration = pulseIn(leftEcho, HIGH);
+ prevLeft = leftDistance;
+ prevRight = rightDistance;
+ //The following trigPin/echoPin cycle is used to determine the
+ //distance of the nearest object by bouncing soundwaves off of it.
  //Calculate the distance (in cm) based on the speed of sound.
  delay(10);
-  digitalWrite(leftTrig, LOW);
-  delayMicroseconds(5);
-  digitalWrite(leftTrig, HIGH);
-  delayMicroseconds(10);
-  digitalWrite(leftTrig, LOW);
-  pinMode(leftEcho, INPUT);
-  durationLeft = pulseIn(leftEcho, HIGH);
+ digitalWrite(leftTrig, LOW);
+ delayMicroseconds(5);
+ digitalWrite(leftTrig, HIGH);
+ delayMicroseconds(10);
+ digitalWrite(leftTrig, LOW);
+ pinMode(leftEcho, INPUT);
+ durationLeft = pulseIn(leftEcho, HIGH);
  leftDistance = durationLeft/58.2;

-  delay(10);
-
-// digitalWrite(rightTrig, LOW);
-// delayMicroseconds(2);
-// digitalWrite(rightTrig, HIGH);
-// delayMicroseconds(10);
-// digitalWrite(rightTrig, LOW);
-// duration = pulseIn(rightEcho, HIGH);
-  digitalWrite(rightTrig, LOW);
-  delayMicroseconds(5);
-  digitalWrite(rightTrig, HIGH);
-  delayMicroseconds(10);
-  digitalWrite(rightTrig, LOW);
-  pinMode(rightEcho, INPUT);
-  durationRight = pulseIn(rightEcho, HIGH);
- //Calculate the distance (in cm) based on the speed of sound.
- rightDistance = durationRight/58.2;
-
-// if((leftDistance<minimumRange)||(leftDistance>maximumRange)) {
-//  leftDistance = prevLeft;
-// }
-// if((rightDistance<minimumRange)||(rightDistance>maximumRange)) {
-//  rightDistance = prevRight;
-// }
-
-//button
-//esc code
-
-// iterator++;
-// leftDistance = 0;
-// rightDistance = 0;
-// for (int j= 0; j < 20; j++) {
-//  leftDistance += lD[j];
-//  rightDistance += rD[j];
-// }
-// leftDistance = leftDistance/20;
-// rightDistance = rightDistance/20;
+ delay(10);
+
+ digitalWrite(rightTrig, LOW);
+ delayMicroseconds(5);
+ digitalWrite(rightTrig, HIGH);
+ delayMicroseconds(10);
+ digitalWrite(rightTrig, LOW);
+ pinMode(rightEcho, INPUT);
+ durationRight = pulseIn(rightEcho, HIGH);
+ rightDistance = durationRight/58.2;
+
+ readLine();
 }

 /*
@@ -186,14 +263,14 @@
 void search() {
   while(!found) {
     // 0 is forward, 1 is backward
-    move(1, 128, rightDir); //right motor
-    move(2, 128, leftDir); //left motor
+    move(1, 200, rightDir); //right motor
+    move(2, 200, leftDir); //left motor
     calcDistance();
     //Serial.print("left: ");
     Serial.print(leftDistance);
     Serial.print(",");
     Serial.println(rightDistance);
-    delay(10);
+    //delay(10);
     if(lost) {
       if(diff>0){//turn right
         rightDir = 0;
@@ -230,14 +307,14 @@
     }

     if(diff > 0 && diffMag > 2) {
-        leftMod = 50*(diffMag/rightDistance);
+        leftMod = 100*(diffMag/rightDistance);
         //Serial.println("R");
     } else if(diff < 0 && diffMag > 2) {
-        rightMod = 50*(diffMag/leftDistance);
+        rightMod = 100*(diffMag/leftDistance);
         //Serial.println("L");
     } else {
-        leftMod = 50;
-        rightMod = 50;
+        leftMod = 100;
+        rightMod = 100;
         //Serial.println("F");
     }
     leftSpeed = baseSpeed + leftMod;
@@ -251,19 +328,3 @@
     move(2, rightSpeed, 0);
   }
 }
-
-  /*
-   * loop
-   * move toward object
-   *    if left sensor is closer, slight turn left
-   *    if right sensor is closer, slight turn right
-   *    if both are pretty much same, keep straight
-   *    stop when both sensor's distance is lower than 10
-   * have a constant for the degree of turn
-   *
-   * if robot loses sight (sensors output -1, do search again)
-   */
-
-
-
-


Press ABCD in video playback mode to skip 1 min

--- Arduino/LightPlayer/LightPlayer.ino
+++ Arduino/LightPlayer/LightPlayer.ino
@@ -61,6 +61,7 @@
   uint8_t reduce_speed;
   uint8_t increase_speed;
   uint8_t toggle_pause;
+  uint8_t skip_forward;

   uint8_t toggle_negative;
   uint8_t reset_settings;
@@ -121,6 +122,10 @@
 int8_t frame_len;
 const int8_t MIN_FRAME_LEN = -1; // Each frame lasts 0.5x normal time (25ms shorter)
 const int8_t MAX_FRAME_LEN = 4;  // Each frame lasts 3x normal time (100ms longer)
+
+const int SKIP_SECONDS = 60;
+const int FPS = 20;
+const int32_t SKIP_BYTES = int32_t(sizeof(frame)) * FPS * SKIP_SECONDS;

 //------------------------------------------------------------------------------
 // File system object.
@@ -217,6 +222,7 @@
   if (ops.reduce_speed)        Serial.print(F("\nreduce_speed"));
   if (ops.increase_speed)      Serial.print(F("\nincrease_speed"));
   if (ops.toggle_pause)        Serial.print(F("\ntoggle_pause"));
+  if (ops.skip_forward)        Serial.print(F("\nskip_forward"));
   if (ops.toggle_negative)     Serial.print(F("\ntoggle_negative"));
   if (ops.reset_settings)      Serial.print(F("\nreset_settings"));
   if (ops.toggle_frame_len)    Serial.print(F("\ntoggle_frame_len"));
@@ -275,6 +281,7 @@
   if (ops.reduce_speed)        speed = max(speed-1, MIN_SPEED);
   if (ops.increase_speed)      speed = min(speed+1, MAX_SPEED);
   if (ops.toggle_pause)        speed = (speed == -1 ? 0 : -1);
+  if (ops.skip_forward)        infile->seekCur(min(((FatFile*)infile)->available(), SKIP_BYTES));
   if (ops.toggle_negative)     negative = !negative;
   if (ops.reset_settings)      resetDefaultSettings();
   if (ops.toggle_frame_len)    frame_len = (frame_len == MAX_FRAME_LEN ? MIN_FRAME_LEN : frame_len+1);
@@ -292,6 +299,7 @@
        || ops.reduce_speed
        || ops.increase_speed
        || ops.toggle_pause
+       || ops.skip_forward
        || ops.toggle_negative
        || ops.reset_settings
        || ops.toggle_frame_len)
@@ -405,6 +413,10 @@

         case Pressed::bd: {
           GlobalPendingOperations.next_video = 1;
+        } break;
+
+        case Pressed::abcd: {
+          GlobalPendingOperations.skip_forward = 1;
         } break;
       }
     } break;


Add LED for final board

Add LED for final board

--- ArduinoSPISlave/ArduinoSPISlave.ino
+++ ArduinoSPISlave/ArduinoSPISlave.ino
@@ -36,6 +36,8 @@

 #define DATA_LEN 5

+#define LED_PIN 7
+
 #define _DEBUG 0

 char control_data[2] = {0xFF,0xFF};
@@ -73,6 +75,24 @@
   SPDR=0xFF;

   sei(); // Enable global interrupts.
+
+  // Indicate Reset
+  pinMode(LED_PIN, OUTPUT);
+  digitalWrite(LED_PIN, HIGH);
+  delay(500);
+  digitalWrite(LED_PIN, LOW);
+  delay(70);
+  digitalWrite(LED_PIN, HIGH);
+  delay(70);
+  digitalWrite(LED_PIN, LOW);
+  delay(70);
+  digitalWrite(LED_PIN, HIGH);
+  delay(70);
+  digitalWrite(LED_PIN, LOW);
+  delay(70);
+  digitalWrite(LED_PIN, HIGH);
+  delay(70);
+  digitalWrite(LED_PIN, LOW);

   if (_DEBUG) {
     Serial.println("");
@@ -141,6 +161,13 @@
     data_buff[2] = lowByte(control_data[0]);
     data_buff[3] = lowByte(control_data[1]);

+    // Led
+    if (lowByte(control_data[0]) != 255 || lowByte(control_data[1]) != 255){
+      digitalWrite(LED_PIN, HIGH);
+    } else {
+      digitalWrite(LED_PIN, LOW);
+    }
+
   }

 }


Add support for DVD player buttons

Add support for DVD player buttons

--- BlinkenScreen.ino
+++ BlinkenScreen.ino
@@ -2,7 +2,18 @@

 SPISettings spi_settings(2000, LSBFIRST, SPI_MODE0);

-const int BUFFER_SIZE = 6;
+#define BUFFER_SIZE 6   // Size of screen frame buffer
+#define BUTTON_PIN  7   // Analog pin 7
+#define BUTTON_THRESHOLD 5 // How many cycles before button considered pressed
+
+// Buttons
+#define BIDLE 10 // Nothing pressed
+#define B1 5
+#define B2 4
+#define B3 3
+#define B4 7
+#define B5 2
+#define B6 0

 typedef union screen {
   char b[BUFFER_SIZE];
@@ -67,12 +78,39 @@
 }

 void setup() {
-//  Serial.begin(9600);
+  Serial.begin(115200);
   SPI.begin();

   s.i = 0;
 }
-
+
+char button_last;
+char button_confidence = 0;
+char read_buttons()
+{
+  char val = analogRead(BUTTON_PIN) / 100; // Analog values are in the hundreds
+
+  // Keep track of how many loops we've been the
+  // same value
+  if (val == button_last) {
+    if (button_confidence <= BUTTON_THRESHOLD) {
+      button_confidence++;
+    }
+  } else {
+    button_confidence = 0;
+    button_last = val;
+    return 0;
+  }
+
+  // Only consider a button pressed if we've
+  // seen the same value for five loops
+  if (button_confidence != 5) {
+    return 0;
+  }
+
+  return val;
+}
+
 char mode = 0;
 void loop() {
   s.i = 1;
@@ -90,5 +128,6 @@
     s.i = s.i << 1;

     delay(80);
+    Serial.println((int)read_buttons());
   }
 }