Main code refactored. Fifth Player added

--- code/PABS/PABS.ino
+++ code/PABS/PABS.ino
@@ -14,12 +14,16 @@
 void setup()
 {
 	Serial.begin(9600);
+
 	pinMode(Constants.adminStartButton, INPUT_PULLUP);
 	pinMode(Constants.adminResetButton, INPUT_PULLUP);
+
 	pinMode(Constants.firstPlayerButton, INPUT_PULLUP);
 	pinMode(Constants.secondPlayerButton, INPUT_PULLUP);
 	pinMode(Constants.thirdPlayerButton, INPUT_PULLUP);
 	pinMode(Constants.fourthPlayerButton, INPUT_PULLUP);
+	pinMode(Constants.fifthPlayerButton, INPUT_PULLUP);
+
 	pinMode(Constants.speakerPin, OUTPUT);
 	pinMode(Constants.ledShiftRegisterClk, OUTPUT);
 	pinMode(Constants.ledShiftRegisterData, OUTPUT);
@@ -31,7 +35,7 @@
 	SystemMethodsObject.PlaySound(1000, 1000);
 	Serial.write("Started!");

-	/*int state = 0;
+	int state = 0;
 	while (digitalRead(Constants.adminStartButton) == HIGH)
 	{
 		SystemMethodsObject.SetDisplayNumber(state);
@@ -48,81 +52,51 @@

 	delay(500);

-	if (state == 0)
+	switch (state)
 	{
-		SystemMethodsObject.SetDisplayNumber(11);
-		gameMode = new TestMode();
-		Serial.write("TestMode");
-		SetupPlayerInts();
-	}
-	else
-	{
-		if (state == 1)
-		{
+		case 0:
+			SystemMethodsObject.SetDisplayNumber(11);
+			gameMode = new TestMode();
+			Serial.write("TestMode");
+			SetupPlayerInts();
+			break;
+		case 1:
 			SystemMethodsObject.SetDisplayNumber(22);
 			gameMode = new BrainRingMode();
 			Serial.write("BrainMode");
 			SetupPlayerInts();
-		}
-		else
-		{
-			if (state == 2)
-			{
-				SystemMethodsObject.SetDisplayNumber(33);
-				gameMode = new OwnGameMode();
-				Serial.write("OwnGameMode");
-				SetupPlayerInts();
-			}
-			else
-			{
-				if (state == 3)
-				{
-					SystemMethodsObject.SetDisplayNumber(44);
-					gameMode = new WwwMode();
-					Timer1.initialize(1000000);
-					Timer1.attachInterrupt(TimerInterrupt);
-					Serial.write("WwwMode!");
-				}
-				else
-				{
-					if (state == 4)
-					{
-						SystemMethodsObject.SetDisplayNumber(55);
-						gameMode = new BrainRingWithTimerMode();
-						Timer1.initialize(1000000);
-						Timer1.attachInterrupt(TimerInterrupt);
-						Serial.write("BrainRingWithTimerMode!");
-					}
-				}
-			}
-		}
+			break;
+		case 2:
+			SystemMethodsObject.SetDisplayNumber(33);
+			gameMode = new OwnGameMode();
+			Serial.write("OwnGameMode");
+			SetupPlayerInts();
+			break;
+		case 3:
+			SystemMethodsObject.SetDisplayNumber(44);
+			gameMode = new WwwMode();
+			Timer1.initialize(1000000);
+			Timer1.attachInterrupt(TimerInterrupt);
+			Serial.write("WwwMode!");
+			break;
+		case 4:
+			SystemMethodsObject.SetDisplayNumber(55);
+			gameMode = new BrainRingWithTimerMode();
+			Timer1.initialize(1000000);
+			Timer1.attachInterrupt(TimerInterrupt);
+			Serial.write("BrainRingWithTimerMode!");
+			break;
+		default:
+			break;
 	}

 	SystemMethodsObject.SetUserLed(-1);
 	SystemMethodsObject.PlaySound(2000, 1000);
-	SetupAdminInts();*/
+	SetupAdminInts();
+
 }

-void loop()
-{
-	for (int i = 0; i < 4; i++)
-	{
-		SystemMethodsObject.SetUserLed(i);
-		//SystemMethodsObject.SetDisplayNumber(i);
-		delay(1000);
-	}
-
-
-	digitalWrite(Constants.displayShiftRegisterRefresh, HIGH);
-	digitalWrite(Constants.displayShiftRegisterClk, HIGH);
-	digitalWrite(Constants.displayShiftRegisterData, HIGH);
-
-
-	/*digitalWrite(Constants.ledShiftRegisterClk, HIGH);
-	digitalWrite(Constants.ledShiftRegisterData, HIGH);
-	digitalWrite(Constants.ledShiftRegisterRefresh, HIGH);
-	digitalWrite(17, HIGH);*/
-}
+void loop(){}

 void SetupAdminInts()
 {
@@ -135,14 +109,13 @@
 	enableInterrupt(Constants.firstPlayerButton, Player1Push, RISING);
 	enableInterrupt(Constants.secondPlayerButton, Player2Push, RISING);
 	enableInterrupt(Constants.thirdPlayerButton, Player3Push, RISING);
-	enableInterrupt(Constants.fourthPlayerButton, Player4Push, RISING);
+	enableInterrupt(Constants.fourthPlayerButton, Player4Push, RISING);
+	enableInterrupt(Constants.fifthPlayerButton, Player5Push, RISING);
 }

 void AdminStartPush()
 {
 	noInterrupts();
-	byte piind = PIND;
-	Serial.print(piind);
 	Serial.println("Admin start pressed!");
 	gameMode->AdminButtonPush(Constants.adminSet);
 	interrupts();
@@ -151,8 +124,6 @@
 void AdminResetPush()
 {
 	noInterrupts();
-	byte piind = PIND;
-	Serial.print(piind);
 	Serial.println("Admin reset pressed!");
 	gameMode->AdminButtonPush(Constants.adminReset);
 	interrupts();
@@ -190,6 +161,14 @@
 	interrupts();
 }

+void Player5Push()
+{
+	noInterrupts();
+	Serial.write("Player 5 pressed!");
+	gameMode->PlayerButtonPush(Constants.player5);
+	interrupts();
+}
+
 void TimerInterrupt()
 {
 	gameMode->TimerPush();


Update for Arduino 1.x.x random function

--- examples/pcdtest/pcdtest.ino
+++ examples/pcdtest/pcdtest.ino
@@ -188,13 +188,13 @@

 void testdrawbitmap(const uint8_t *bitmap, uint8_t w, uint8_t h) {
   uint8_t icons[NUMFLAKES][3];
-  srandom(666);     // whatever seed
+  randomSeed(666);     // whatever seed

   // initialize
   for (uint8_t f=0; f< NUMFLAKES; f++) {
-    icons[f][XPOS] = random() % display.width();
+    icons[f][XPOS] = random(display.width());
     icons[f][YPOS] = 0;
-    icons[f][DELTAY] = random() % 5 + 1;
+    icons[f][DELTAY] = random(5) + 1;

     Serial.print("x: ");
     Serial.print(icons[f][XPOS], DEC);
@@ -219,9 +219,9 @@
       icons[f][YPOS] += icons[f][DELTAY];
       // if its gone, reinit
       if (icons[f][YPOS] > display.height()) {
-	icons[f][XPOS] = random() % display.width();
+	icons[f][XPOS] = random(display.width());
 	icons[f][YPOS] = 0;
-	icons[f][DELTAY] = random() % 5 + 1;
+	icons[f][DELTAY] = random(5) + 1;
       }
     }
    }


decreased tsopstrength for ball to be in capture zone

--- master/master.ino
+++ master/master.ino
@@ -871,7 +871,7 @@
 	laserSig = analogRead(LASER_SIG);
 	if (laserSig < LASER_REF
 	 && abs(tsopAngle) < 30
-	 && tsopStrength > 150){
+	 && tsopStrength > 140){
 		ballInZone = true;
 	}
 	else{


Reduce the size of the sketch a bit.

Reduce the size of the sketch a bit.

Technically, this LED flash is debug code.

With DEBUG off, the sketch is 27906 bytes.

--- wee_printer.ino
+++ wee_printer.ino
@@ -6,7 +6,7 @@
 #include <Thermal.h>
 #include <Bounce.h>

-#define DEBUG
+//#define DEBUG
 #ifdef DEBUG
 #define debug(a) Serial.print(millis()); Serial.print(": "); Serial.println(a);
 #define debug2(a, b) Serial.print(millis()); Serial.print(": "); Serial.print(a); Serial.println(b);
@@ -67,7 +67,9 @@
   initSD();
   initNetwork();
   initPrinter();
+#ifdef DEBUG
   initDiagnosticLEDs();
+#endif
 }

 //const char* host = "192.168.1.22"; // uberatom


Version 2.54. Wi-Fi disabled until logging system is in place.

--- module/module.ino
+++ module/module.ino
@@ -62,6 +62,7 @@
 			Serial.print(messages.displayUsedTime);
 			Serial.println(existingTime);
 			Serial.print(messages.authorized);
+			// get ready to record time
 			elapsedTime = accumulator();
 			Serial.print(messages.displayNewTime);
 			Serial.println(elapsedTime + existingTime);
@@ -80,7 +81,7 @@
 		else {
 			Serial.print(messages.cardUpdated);
 			delay(timeToRemoveCard);
-			wifiReady = true;
+			wifiReady = false;
 		}
 	}
 	else {
@@ -93,14 +94,16 @@
 		startConnection();
 		GET();
 		bool done = false;
+		unsigned long httpTime = millis();
 		while (!done) {
 			while (WIFI.available()) {
 				Serial.write(WIFI.read());
 			}
-			if(digitalRead(speakerPin) == HIGH) {
+			if ((millis() - httpTime) > 3*pollInterval) {
 				done = true;
 			}
 		}
+		closeConnection();
 		Serial.println();
 		RFID.listen();
 	}


Set User ID to test

Set User ID to test

--- module/module.ino
+++ module/module.ino
@@ -230,7 +230,7 @@
 						delay(sendInterval);
 					}
 					startConnection();
-					updateThingSpeak(0, sendCount);
+					updateThingSpeak(1, sendCount);
 					lastSend = millis();
 					sendCount = 0;
 					Serial.println("Done");


Initialized boolean array explicitly

Initialized boolean array explicitly

--- module/module.ino
+++ module/module.ino
@@ -155,7 +155,7 @@
 	unsigned int pulseCount = 0;
 	unsigned int pollCounter = 0;
 	int i = 0;
-	bool signals[sampleSize];
+	bool signals[] = {0,0,0};

 	// Only here temporarily for debugging
 	if (debug) {


Added approved experimental code to master branch -- TODO: Must add test cases and ensure that source code in cold-brew.ino is ported to cold-brew.h

--- cold-brew.ino
+++ cold-brew.ino
@@ -1,13 +1,15 @@
 #include <FiniteStateMachine.h>
 #include <Adafruit_NeoPixel.h>

-#define DRAIN_MTR 6
+#define DEBUG
+#define DRAIN_MTR 8
 #define VALV_ATM 7
-#define VACU_PUMP	8
+#define VACU_PUMP	6
 #define CAP_TCH     A6
 #define PRS_SEN 10
 #define NEOPIX  5
 #define NUM_OF_PIX 12
+#define MECH_SWT 9

 //  Tell compiler that functions exist, just implementated later
 extern void idled();
@@ -20,6 +22,10 @@

 ////	Define the states within the SM

+const unsigned long TIME_FOR_MTR_TO_OPEN_LID = 210;
+const unsigned long PULSE_TIME = 10;
+const unsigned long DISSIPATE_TIME = 100;
+
 // Idle state
 State idle_state = State(idled);

@@ -36,13 +42,21 @@
 FSM stateMachine = FSM(idle_state);		//	Initial SM with beginning state

 unsigned long startTime;			//	Used to track times for Vacuum/Dwell timer
-unsigned long setTimeLimit = 120000;		//	User defined time limit
-
+
+/********** TIMEOUT FOR SUM OF VACUUM AND DWELL TIMES **********/
+//unsigned long setTimeLimit = 60000;	// Test
+unsigned long setTimeLimit = 480000;		//	User defined time limit
+
+
+/********** TIMEOUT FOR DRAIN TIME **********/
+//unsigned long drainTimeout = 10000;   // Test
+unsigned long drainTimeout = 240000;
+
+
+/********** Other variables...  **********/
 unsigned long stateStartTime;			//	Used to track times for entering Vacuum/Dwell states
 unsigned long stateDebounceLimit = 30000;	//	Used to define state debounce time limit
 unsigned long vacuDebounceLimit = 1000;    //  Used to define state debounce time limit
-
-unsigned long drainTimeout = 60000;

 int buttonState;             // the current reading from the input pin
 int lastButtonState = HIGH;   // the previous reading from the input pin
@@ -56,10 +70,10 @@
 Adafruit_NeoPixel ledStat = Adafruit_NeoPixel(NUM_OF_PIX, NEOPIX, NEO_GRB + NEO_KHZ800);		//	Neopixel initializiation

 /*************************** COLOR FOR MODES  ***************************/
-uint32_t idleLEDColor = ledStat.Color(0, 255, 0);			// Green
-uint32_t vacuumLEDColor = ledStat.Color(255, 255, 0);		// Yellow
-uint32_t dwellLEDColor = ledStat.Color(238, 130, 238);   // Purple
-uint32_t drainLEDColor = ledStat.Color(255, 0, 0);		// Red
+uint32_t idleLEDColor = ledStat.Color(0, 255, 0);           // Green
+uint32_t vacuumLEDColor = ledStat.Color(0, 0, 255);     // Blue
+uint32_t dwellLEDColor = ledStat.Color(255, 255, 255);   // White
+uint32_t drainLEDColor = ledStat.Color(255, 0, 0);      // Red

 void setup() {
 	Serial.begin(9600);
@@ -68,6 +82,7 @@
 	pinMode(VACU_PUMP, OUTPUT);
 	pinMode(PRS_SEN, INPUT_PULLUP);
 	pinMode(CAP_TCH, INPUT);
+	pinMode(MECH_SWT, INPUT_PULLUP);
 	ledStat.begin();
 }

@@ -104,11 +119,15 @@
             switch (buttonPresses){
                 case IDLED:
                 	Serial.println("IDLE");
+					closeArmIntoClosedLidState();
                		stateMachine.transitionTo(idle_state);
                 	break;

                 case VACU:
                 	Serial.println("VACU");
+
+					closeArmIntoClosedLidState();
+
                    	//  Begin timer for total time between Vacuum and Dwell states
                    	startTime = millis();
 					stateStartTime = millis();
@@ -126,6 +145,7 @@

                 case DRIN:
                 	Serial.println("DRIN");
+					moveArmIntoDrainOpenState();
 					stateStartTime = millis();
                 	stateMachine.transitionTo(drin_state);
                 	break;
@@ -134,10 +154,49 @@
         }
     }

+#ifdef DEBUG
+//    if ((millis() % 1000) == 0) {
+//        Serial.print("This is pressure switch");
+//        Serial.println(digitalRead(PRS_SEN));
+//    }
+#endif
+
     lastButtonState = reading;

 	//	Updates the SM for every loop -- APPLICATION CRITICAL
     stateMachine.update();
+}
+
+void moveArmIntoDrainOpenState() {
+	digitalWrite(DRAIN_MTR, HIGH);
+    Serial.println("PREPARING TO DRAIN -- ARM MOVING");
+	delay(TIME_FOR_MTR_TO_OPEN_LID);
+	digitalWrite(DRAIN_MTR, LOW);
+}
+
+void closeArmIntoClosedLidState() {
+	//	At switch state ON (When CAM is pushing against
+	//		push button) CAM is in closed state.
+	//		Default value is OFF, or logic high; switch
+	//		uses input pullup.
+	//static unsigned long currentTime = millis();
+	int mechSwitchResult = digitalRead(MECH_SWT);
+    Serial.println("POST DRAIN -- ARM CLOSING");
+    Serial.print("This is switch value: ");
+    Serial.println(mechSwitchResult);
+	while (mechSwitchResult == HIGH) {
+		digitalWrite(DRAIN_MTR, HIGH);
+		delay(PULSE_TIME);
+		digitalWrite(DRAIN_MTR, LOW);
+		delay(DISSIPATE_TIME);
+		mechSwitchResult = digitalRead(MECH_SWT);
+		if (mechSwitchResult == LOW) {
+			Serial.println("THIS IS EVAL TO TRUE");
+		}
+	}
+    Serial.print("This is switch value 2: ");
+    Serial.println(digitalRead(MECH_SWT));
+	digitalWrite(DRAIN_MTR, LOW);
 }

 void setPixelRingColor(uint32_t val) {
@@ -180,6 +239,7 @@
 		//	Ensure that next button press in DRAIN state will lead to IDLE
 		buttonPresses = 3;

+        moveArmIntoDrainOpenState();
        	stateMachine.immediateTransitionTo(drin_state);
    	} else if ((digitalRead(PRS_SEN) == LOW) && ((millis() - stateStartTime) > vacuDebounceLimit)) {
     	//	If the pressure is at or above the calibrated sensor threshold
@@ -219,6 +279,7 @@
 		//	Ensure that next button press in DRAIN state will lead to IDLE
 		buttonPresses = 3;

+        moveArmIntoDrainOpenState();
 		stateMachine.immediateTransitionTo(drin_state);
 	} else if ((digitalRead(PRS_SEN) == HIGH) && ((millis() - stateStartTime) > stateDebounceLimit)) {
     	//	If pressure is below set pressure threshold, return to
@@ -238,7 +299,7 @@
 	// Close pump valve, turn off pump, and open the atmosphere valve
 	//	to equalize with external pressure.
 	digitalWrite(VACU_PUMP, LOW);
-	digitalWrite(DRAIN_MTR, HIGH);
+	//digitalWrite(DRAIN_MTR, LOW);
 	digitalWrite(VALV_ATM, HIGH);

 	setPixelRingColor(drainLEDColor);
@@ -247,6 +308,7 @@

 void drainUpdate() {
 	if((millis() - stateStartTime) >  drainTimeout) {
+		closeArmIntoClosedLidState();
 		stateMachine.transitionTo(idle_state);
 	}
 }


version 2

version 2

--- taqi/taqi.ino
+++ taqi/taqi.ino
@@ -1,358 +1,367 @@
-//#define __DEBUG__
+//#define __DEBUG__
+
+#define threshold 200
+#define baud 9600
+#define short_del 500
+#define long_del 2000
+
+unsigned int new_pin1 = A4;
+unsigned int new_pin2 = A5;
+
+const unsigned int red[] = {10, 7, new_pin1, 13}; //r1, r2, r3, r4
+const unsigned int yellow[] = {9, 6, new_pin2, 12};
+const unsigned int green[] = {8, 5, 4, 11};
+
+int ir1 = 0;
+int ir2 = 1;
+int ir3 = 2;
+int ir4 = 3;
+
+int ir[] = {ir1, ir2, ir3, ir4};
+
+bool reading[] = {false, false, false, false};
+
+enum LIGHT {FIRST = 0, SECOND = 1, THIRD = 2, FOURTH = 3, NONE = 4};
+
+LIGHT light;
+
+int index = 4;
+
+void debug(void){
+  Serial.println (" == DEBUG BEGIN == ");
+  for (int i = 0; i < 4; i++){
+    Serial.println("IR [ " + String(i) + "] = " + String(analogRead(ir[i])));
+    delay(short_del);
+  }
+  Serial.println (" == DEBUG END == ");
+  Serial.println();
+  delay(long_del);
+}
+
+void setup() {
+  Serial.begin(baud);
+  for (int i = 0; i < 4; i++){
+    pinMode(red[i], OUTPUT);
+    pinMode(yellow[i], OUTPUT);
+    pinMode(green[i], OUTPUT);
+    pinMode(ir[i], INPUT);
+  }
+}
+
+int whichLight(void){
+  if (analogRead(ir[0]) < threshold) return FIRST;
+  else if (analogRead(ir[1]) < threshold) return SECOND;
+  else if (analogRead(ir[2]) < threshold) return THIRD;
+  else if (analogRead(ir[3]) < threshold) return FOURTH;
+  else return NONE;
+}
+
+void offAll (void){
+  for (int i = 0; i < 4; i++){
+    digitalWrite (red[i], LOW);
+    digitalWrite (yellow[i], LOW);
+    digitalWrite (green[i], LOW);
+  }
+}
+
+void firstLight(void){
+  offAll();
+  digitalWrite (green[FIRST], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+}
+
+void secondLight(void){
+  offAll();
+  digitalWrite(green[SECOND], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+}
+
+
+void thirdLight(void){
+  offAll();
+  digitalWrite(green[THIRD], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+}
+
+void fourthLight(void){
+  offAll();
+  digitalWrite(green[FOURTH], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+}
+
+
+void onAll(void){
+  for (int i = 0; i < 4; i++) {
+    digitalWrite(red[i], HIGH);
+    digitalWrite(yellow[i], HIGH);
+    digitalWrite(green[i], HIGH);
+  }
+}
+
+
+void onIdle(void){
+
+  index = whichLight();
+
+  // For first light
+  digitalWrite(green[FIRST], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+  delay(long_del);
+  digitalWrite(green[FIRST], LOW);
+  digitalWrite(red[SECOND], LOW);
+  digitalWrite(red[THIRD], LOW);
+  digitalWrite(red[FOURTH], LOW);
+
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
+  delay(short_del);
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
+
+  index = whichLight();
+
+  //For second
+  digitalWrite(green[SECOND], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+  delay(long_del);
+  digitalWrite(green[SECOND], LOW);
+  digitalWrite(red[FIRST], LOW);
+  digitalWrite(red[THIRD], LOW);
+  digitalWrite(red[FOURTH], LOW);
+
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
+  delay(short_del);
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
+
+  index = whichLight();
+
+  //For third
+  digitalWrite(green[THIRD], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+  delay(long_del);
+  digitalWrite(green[THIRD], LOW);
+  digitalWrite(red[FIRST], LOW);
+  digitalWrite(red[SECOND], LOW);
+  digitalWrite(red[FOURTH], LOW);
+
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
+  delay(short_del);
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
+
+  index = whichLight();
+
+  //For fourth
+  digitalWrite(green[FOURTH], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+  delay(long_del);
+  digitalWrite(green[FOURTH], LOW);
+  digitalWrite(red[FIRST], LOW);
+  digitalWrite(red[SECOND], LOW);
+  digitalWrite(red[THIRD], LOW);
+
+  index = whichLight();
+
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
+  delay(short_del);
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
+
+}
+
+#ifdef __DEBUG__
+void loop() { onAll(); }
+
+#else
+
+
+
+void loop(){
+
+  int index = 4;
+
+  index = whichLight();
+
+  while(index != NONE){
+    index = whichLight();
+    switch(index){
+      case FIRST:
+        firstLight();
+        break;
+      case SECOND:
+        secondLight();
+        break;
+
+      case THIRD:
+        thirdLight();
+        break;
+
+      case FOURTH:
+        fourthLight();
+        break;
+
+      default:
+        offAll();
+        break;
+    }
+  }
+
+  while(whichLight() == NONE){
+
+  if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+
+      // For first light
+  digitalWrite(green[FIRST], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  delay(long_del);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  digitalWrite(green[FIRST], LOW);
+  digitalWrite(red[SECOND], LOW);
+  digitalWrite(red[THIRD], LOW);
+  digitalWrite(red[FOURTH], LOW);
+  index = whichLight();
+
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
+  index = whichLight();
+  delay(short_del);
+  index = whichLight();
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
+
+  index = whichLight();
+
+  //For second
+  digitalWrite(green[SECOND], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  delay(long_del);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  digitalWrite(green[SECOND], LOW);
+  digitalWrite(red[FIRST], LOW);
+  digitalWrite(red[THIRD], LOW);
+  digitalWrite(red[FOURTH], LOW);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  delay(short_del);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
+
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+
+  //For third
+  digitalWrite(green[THIRD], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+  digitalWrite(red[FOURTH], HIGH);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  delay(long_del);
+  digitalWrite(green[THIRD], LOW);
+  digitalWrite(red[FIRST], LOW);
+  digitalWrite(red[SECOND], LOW);
+  digitalWrite(red[FOURTH], LOW);
+
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  delay(short_del);
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+
+
+  //For fourth
+  digitalWrite(green[FOURTH], HIGH);
+  digitalWrite(red[FIRST], HIGH);
+  digitalWrite(red[SECOND], HIGH);
+  digitalWrite(red[THIRD], HIGH);
+
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+
+  delay(long_del);
+  digitalWrite(green[FOURTH], LOW);
+  digitalWrite(red[FIRST], LOW);
+  digitalWrite(red[SECOND], LOW);
+  digitalWrite(red[THIRD], LOW);
+
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+  delay(short_del);
+  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
+
+    if (whichLight() != NONE){
+    offAll();
+    break;
+  }
+
+  }
+}
+
+
+#endif

-#define threshold 500
-#define baud 9600
-#define short_del 500
-#define long_del 2000
-
-const unsigned int red[] = {10, 7, 2, 13}; //r1, r2, r3, r4
-const unsigned int yellow[] = {9, 6, 3, 12};
-const unsigned int green[] = {8, 5, 4, 11};
-const unsigned int ir[] = {0, 1, 2, 3};
-
-bool reading[] = {false, false, false, false};
-
-enum LIGHT {FIRST = 0, SECOND = 1, THIRD = 2, FOURTH = 3, NONE = 4};
-
-LIGHT light;
-
-int index = 4;
-
-void debug(void){
-  Serial.println (" == DEBUG BEGIN == ");
-  for (int i = 0; i < 4; i++){
-    Serial.println("IR [ " + String(i) + "] = " + String(analogRead(ir[i])));
-    delay(short_del);
-  }
-  Serial.println (" == DEBUG END == ");
-  Serial.println();
-  delay(long_del);
-}
-
-void setup() {
-  Serial.begin(baud);
-  for (int i = 0; i < 4; i++){
-    pinMode(red[i], OUTPUT);
-    pinMode(yellow[i], OUTPUT);
-    pinMode(green[i], OUTPUT);
-    pinMode(ir[i], INPUT);
-  }
-}
-
-int whichLight(void){
-  if (analogRead(ir[0]) < threshold) return FIRST;
-  else if (analogRead(ir[1]) < threshold) return SECOND;
-  else if (analogRead(ir[2]) < threshold) return THIRD;
-  else if (analogRead(ir[3]) < threshold) return FOURTH;
-  else return NONE;
-}
-
-void offAll (void){
-  for (int i = 0; i < 4; i++){
-    digitalWrite (red[i], LOW);
-    digitalWrite (yellow[i], LOW);
-    digitalWrite (green[i], LOW);
-  }
-}
-
-void firstLight(void){
-  offAll();
-  digitalWrite (green[FIRST], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-}
-
-void secondLight(void){
-  offAll();
-  digitalWrite(green[SECOND], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-}
-
-
-void thirdLight(void){
-  offAll();
-  digitalWrite(green[THIRD], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-}
-
-void fourthLight(void){
-  offAll();
-  digitalWrite(green[FOURTH], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-}
-
-
-void onAll(void){
-  for (int i = 0; i < 4; i++) {
-    digitalWrite(red[i], HIGH);
-    digitalWrite(yellow[i], HIGH);
-    digitalWrite(green[i], HIGH);
-  }
-}
-
-
-void onIdle(void){
-
-  index = whichLight();
-
-  // For first light
-  digitalWrite(green[FIRST], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-  delay(long_del);
-  digitalWrite(green[FIRST], LOW);
-  digitalWrite(red[SECOND], LOW);
-  digitalWrite(red[THIRD], LOW);
-  digitalWrite(red[FOURTH], LOW);
-
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
-  delay(short_del);
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
-
-  index = whichLight();
-
-  //For second
-  digitalWrite(green[SECOND], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-  delay(long_del);
-  digitalWrite(green[SECOND], LOW);
-  digitalWrite(red[FIRST], LOW);
-  digitalWrite(red[THIRD], LOW);
-  digitalWrite(red[FOURTH], LOW);
-
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
-  delay(short_del);
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
-
-  index = whichLight();
-
-  //For third
-  digitalWrite(green[THIRD], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-  delay(long_del);
-  digitalWrite(green[THIRD], LOW);
-  digitalWrite(red[FIRST], LOW);
-  digitalWrite(red[SECOND], LOW);
-  digitalWrite(red[FOURTH], LOW);
-
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
-  delay(short_del);
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
-
-  index = whichLight();
-
-  //For fourth
-  digitalWrite(green[FOURTH], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-  delay(long_del);
-  digitalWrite(green[FOURTH], LOW);
-  digitalWrite(red[FIRST], LOW);
-  digitalWrite(red[SECOND], LOW);
-  digitalWrite(red[THIRD], LOW);
-
-  index = whichLight();
-
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
-  delay(short_del);
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
-
-}
-
-#ifdef __DEBUG__
-void loop() { onAll(); }
-
-#else
-
-
-
-void loop(){
-
-  int index = 4;
-
-  index = whichLight();
-
-  while(index != NONE){
-    index = whichLight();
-    switch(index){
-      case FIRST:
-        firstLight();
-        break;
-      case SECOND:
-        secondLight();
-        break;
-
-      case THIRD:
-        thirdLight();
-        break;
-
-      case FOURTH:
-        fourthLight();
-        break;
-
-      default:
-        offAll();
-        break;
-    }
-  }
-
-  while(whichLight() == NONE){
-
-  if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-
-      // For first light
-  digitalWrite(green[FIRST], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  delay(long_del);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  digitalWrite(green[FIRST], LOW);
-  digitalWrite(red[SECOND], LOW);
-  digitalWrite(red[THIRD], LOW);
-  digitalWrite(red[FOURTH], LOW);
-  index = whichLight();
-
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
-  index = whichLight();
-  delay(short_del);
-  index = whichLight();
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
-
-  index = whichLight();
-
-  //For second
-  digitalWrite(green[SECOND], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  delay(long_del);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  digitalWrite(green[SECOND], LOW);
-  digitalWrite(red[FIRST], LOW);
-  digitalWrite(red[THIRD], LOW);
-  digitalWrite(red[FOURTH], LOW);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  delay(short_del);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
-
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-
-  //For third
-  digitalWrite(green[THIRD], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-  digitalWrite(red[FOURTH], HIGH);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  delay(long_del);
-  digitalWrite(green[THIRD], LOW);
-  digitalWrite(red[FIRST], LOW);
-  digitalWrite(red[SECOND], LOW);
-  digitalWrite(red[FOURTH], LOW);
-
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  delay(short_del);
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-
-
-  //For fourth
-  digitalWrite(green[FOURTH], HIGH);
-  digitalWrite(red[FIRST], HIGH);
-  digitalWrite(red[SECOND], HIGH);
-  digitalWrite(red[THIRD], HIGH);
-
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-
-  delay(long_del);
-  digitalWrite(green[FOURTH], LOW);
-  digitalWrite(red[FIRST], LOW);
-  digitalWrite(red[SECOND], LOW);
-  digitalWrite(red[THIRD], LOW);
-
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], HIGH);
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-  delay(short_del);
-  for (int i = 0; i < 4; i++) digitalWrite(yellow[i], LOW);
-
-    if (whichLight() != NONE){
-    offAll();
-    break;
-  }
-
-  }
-}
-
-
-#endif
-


Several bug fixes for Arduino.

Several bug fixes for Arduino.

--- Arduino/LaserHarpMultiplex/LaserHarpMultiplex.ino
+++ Arduino/LaserHarpMultiplex/LaserHarpMultiplex.ino
@@ -29,7 +29,7 @@
 const int ledPin = 9;

 // Pin for turning lasers on/off
-const int laserPin = 8;
+const int laserPin = 10;

 const int inputCount = 8;  // Number of inputs we are reading. Can be up to 16.

@@ -76,6 +76,8 @@
 {
   ledMode = mode;
   ledNumber = number;
+  lastLed = LOW;
+  digitalWrite(ledPin, LOW);
   updateLed();
 }

@@ -155,7 +157,7 @@
 void displayCalibrationData()
 {
   for (int i = 0; i < inputCount; ++i) {
-    Serial.print(i);
+    Serial.print(i+1);
     Serial.print(": ");
     Serial.print(calibrateMin[i]);
     Serial.print(" to ");
@@ -205,11 +207,12 @@
   int error = -1; // Set to first laser we can't calibrate.
   for (int i = 0; i < inputCount; ++i) {
     thresholds[i] = (minLasersOn[i] + maxLasersOff[i]) / 2;
-    Serial.print(i);
+    Serial.print(i+1);
     Serial.print(": ");
     Serial.print(thresholds[i]);

     if (minLasersOn[i] - maxLasersOff[i] < minCalibrationGap) {
+      thresholds[i] = -1;
       Serial.print("  CALIBRATION FAILED!");
       if (error == -1)
         error = i;
@@ -244,19 +247,24 @@
 }

 const long heartbeat = 1000;  // milliseconds between heartbeats.
+
+long lastTimeHeartbeat, currentTime;
+
 void loop() {
-    long lastTimeHeartbeat, currentTime;

     updateLed();

     currentTime = millis();
     if (currentTime - lastTimeHeartbeat > heartbeat) {
       lastTimeHeartbeat = currentTime;
-      Serial.println('~');
+      Serial.println("~");
     }

     for (int i = 0; i < inputCount; ++i) {
-
+        // Ignore inputs that failed calibration.
+        if (thresholds[i] < 0)
+            continue;
+
         // Read analog input value.
         int value = multiplexedAnalogRead(i);

@@ -266,9 +274,9 @@
         // If different than last value, send notification.
         if (newInput != current[i]) {
             if (newInput)
-              Serial.print('a' + i); // HIGH means laser detected -> interruption OFF
+              Serial.write('a' + i); // HIGH means laser detected -> interruption OFF
             else
-              Serial.print('A' + i); // LOW means laser not detected -> interruption ON
+              Serial.write('A' + i); // LOW means laser not detected -> interruption ON
          }
         current[i] = newInput;
     }


updated speed factor.

updated speed factor.

--- BLEBriteLamp.ino
+++ BLEBriteLamp.ino
@@ -166,7 +166,7 @@
           delayMillis = 1000;  // millisecond delay; default 1 second
         }
         else {
-          delayMillis = speed * 100;
+          delayMillis = speed * 4;
         }
         currentColor = 0;
 //        Serial.print("Delay is ");
@@ -213,3 +213,4 @@
 }

+


Replaced the hang-while-connected code with more loop()-friendly state-driven code

--- DHTBLESensor.ino
+++ DHTBLESensor.ino
@@ -91,9 +91,12 @@
 /*
    Sketch running state variables:

+   bleConnected = true if a BLE device is connected to us; false otherwise.
+
    whenSensedMs = time (millis()) when the sensor was last read
      and the Temperature and Humidity sent via BLE.
 */
+boolean bleConnected = false;
 long whenSensedMs = 0;

 // Called automatically on Reset
@@ -125,29 +128,34 @@
 // Automatically called very often, after setup()
 void loop() {
   BLECentral central = myBLE.central();
-
-  if (central) {
-    digitalWrite(PIN_CONNECTED_LED, HIGH);
-
-    Serial.print("Connected to central: ");
-    Serial.println(central.address());
-
-    //XXX change this into a state machine.
-    while (central.connected()) {  //XXX Not a good idea because connecting hangs all other Arduino functions (like reset and download)
-      long nowMs = millis();
-      if ((long)(nowMs - whenSensedMs) >= TEMPERATURE_UPDATE_INTERVAL_MS) {
-        whenSensedMs = nowMs;
-        if (readTemperatureAndHumidity()) {
-          setBLETemperatureAndHumidity(dht22.temperature, dht22.humidity);
-        }
-      }
-    }
-    // Disconnected
-
-    digitalWrite(PIN_CONNECTED_LED, LOW);
-
-    Serial.print("Disconnected from central: ");
-    Serial.println(central.address());
+  long nowMs;
+
+  // Note the comings and goings of BLE clients (Centrals)
+  if (central && central.connected()) {
+    if (!bleConnected) {
+      bleConnected = true;
+      digitalWrite(PIN_CONNECTED_LED, HIGH);
+      Serial.print("Connected to central: ");
+      Serial.println(central.address());
+    }
+
+    // If we wanted to do something only while connected, we'd do it here.
+
+  } else {
+    if (bleConnected) {
+      bleConnected = false;
+      digitalWrite(PIN_CONNECTED_LED, LOW);
+      Serial.println("Disconnected from central.");
+    }
+  }
+
+  // Periodically read the sensor, regardless of whether anyone's listening.
+  nowMs = millis();
+  if ((long)(nowMs - whenSensedMs) >= TEMPERATURE_UPDATE_INTERVAL_MS) {
+    whenSensedMs = nowMs;
+    if (readTemperatureAndHumidity()) {
+      setBLETemperatureAndHumidity(dht22.temperature, dht22.humidity);
+    }
   }
 }


reset

reset


misc comment cleanup

misc comment cleanup

--- IMUtest.ino
+++ IMUtest.ino
@@ -16,7 +16,8 @@
 long baud = 115200; // 115200; // 9600, 57600, 115200

 // generally have only one of the following set to TRUE, depending upon task
-bool PRINTSCREEN  = true;  // user-friendly print of roll, pitch, heading
+bool PRINTSCREEN  = true;   // compare gyro fusion 'on' to gyro fusion 'off',
+                            // user-friendly print of roll, pitch, heading
 bool RPH          = false;  // roll, pitch, heading, formatted for visual python
 bool RPH2         = false;  // compare gyro fusion 'on' to gyro fusion 'off',
                             // for Processing RealTimePlotter format
@@ -96,17 +97,17 @@

   // true means gyro is used, followed by alpha
   // 0 < alpha < 1;
-  // alpha ~ 1 weights gyro heavily, alpha ~ 0 mall weights accelerometer heavily
+  // alpha ~ 1 weights gyro heavily, alpha ~ 0 weights accelerometer heavily
   // if false, alpha is ignored, and no gyro data is used
   withGyro.setWeightsAndGyro(true, 0.95);
   noGyro.setWeightsAndGyro(false, 0.95); // no gyro, alpha is ignored

-  // mag, acc, calibration method to be updated: take three offsets, three scales
-  // 5/11/17 calib, average of three
+  // mag, acc, calibration methods take three offsets, three scales
+  // 5/11/17 calibration, average of three
   withGyro.setCalibrateMag(  -52, -158,   39,  1.00, 1.02, 1.16);
   noGyro.setCalibrateMag(  -52, -158,   39,  1.00, 1.02, 1.16);

-  // 5/8/17 values
+  // 5/8/17 calibration values
   withGyro.setCalibrateAcc(-1020,  -84, -700,  1.07, 1.07, 1.00);
   noGyro.setCalibrateAcc(-1020,  -84, -700,  1.07, 1.07, 1.00);


Update VCNL4010-tester.ino

Update VCNL4010-tester.ino

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

 vcnl4010 vcnl;


pass added

pass added

--- nodmcu.ino
+++ nodmcu.ino
@@ -100,7 +100,7 @@
           HTTPClient http;
           http.begin(REPOSITORY_HOST);
           http.addHeader("Content-Type", "application/x-www-form-urlencoded");
-          http.POST("id=" + getID() + "&version=" + DEV_VERSION);
+          http.POST("id=" + getID() + "&version=" + DEV_VERSION + "&appkey=" + DHEX);
           String response = http.getString();
           http.end();
           CheckRemoteFeedback(response);
@@ -314,7 +314,7 @@
     WiFiManager wifiManager;

     //it starts an access point and goes into a blocking loop awaiting configuration
-    if (!wifiManager.startConfigPortal("PetFeed")) {
+    if (!wifiManager.startConfigPortal("PetFeed", "12345678")) {
       Serial.println("Not connected to WiFi but continuing anyway.");
     } else {
       //if you get here you have connected to the WiFi


backed up old ethercard-post

backed up old ethercard-post

--- SpaceAPI/SpaceAPI.ino
+++ SpaceAPI/SpaceAPI.ino
@@ -1,31 +1,97 @@
+#include <OneWire.h>
+#include <DallasTemperature.h>
 #include <EtherCard.h>
 #include "secrets.h"

+#define DEBUG false // ignore network if true
+
 // ethernet interface mac address, must be unique on the LAN
-byte mymac[] = { 0x74, 0x69, 0x69, 0x2D, 0x42, 0x42 };
+byte mymac[] = { 0x74, 0x69, 0x69, 0x2D, 0x30, 0x31 };

 // CONFIG:
-#define BAUDRATE 57600
-const char api[]      PROGMEM = "spaceapi.net";
-const char endpoint[] PROGMEM = "new/space/losfuzzyslab/sensor/set";
+#define BAUDRATE 9600
+//const char api[]      PROGMEM = "spaceapi.net";
+//const char endpoint[] PROGMEM = "new/space/losfuzzyslab/sensor/set";
+const char api[]      PROGMEM = "think.2904.cc";
+const char endpoint[] PROGMEM = "losfuzzys/index.php";
+
+#define PIN_ONEWIRE 2
+#define TEMPERATURE_PRECISION 9 // Lower resolution
+
 // define TOKEN in secrets.h
+
+#define DOOR_OPEN 1
+#define DOOR_CLOSED 0
+#define DOOR_ERROR 2

 static byte session;
 byte Ethernet::buffer[700];
 Stash stash;
-bool oldDoorstatus = false;
-
-static void updateDoorstatus(bool isOpen) {
-  Serial.println("[>] Sending new doorstatus ...");
-
+
+float oldTemp = 0;
+int numberOfDevices;
+DeviceAddress tempDeviceAddress;
+OneWire oneWire(PIN_ONEWIRE);
+DallasTemperature sensors(&oneWire);
+
+int oldDoorstatus = DOOR_ERROR;
+
+static void updateTemperature(float temp) {
+  Serial.println("[>] Sending new temperature ...");
+
+  if (DEBUG) return;
+
   byte sd = stash.create();

-  const char s_open[]  = "%7B%22state%22%3A%7B%22open%22%3Atrue%7D%7D";
-  const char s_close[] = "%7B%22state%22%3A%7B%22open%22%3Afalse%7D%7D";
+  ether.dnsLookup(api);
+
   stash.print("key=");
   stash.print(TOKEN);
-  stash.print("&sensors=");
-  stash.println(isOpen ? s_open : s_close);
+  stash.print("&temp=");
+  stash.println(42.0);
+  stash.save();
+  int stash_size = stash.size();
+
+  Stash::prepare(PSTR("POST http://$F/$F HTTP/1.0" "\r\n"
+                      "Host: $F" "\r\n"
+                      "Content-Type: application/x-www-form-urlencoded \r\n"
+                      "Content-Length: $D" "\r\n"
+                      "\r\n"
+                      "$H"),
+                 api, endpoint, api, stash_size, sd);
+
+  Serial.println(Stash::length());
+  for (word i = 0, n = Stash::length(); i < n; ++i)
+  {
+    char c;
+    Stash::extract(i, 1, &c);
+    Serial.print(c);
+  }
+  Serial.println();
+
+  // send the packet - this also releases all stash buffers once done
+  // Save the session ID so we can watch for it in the main loop.
+  session = ether.tcpSend();
+
+  Serial.println("[>] Done sending temperature!");
+}
+
+static void updateDoorstatus(int isOpen) {
+  Serial.println("[>] Sending new doorstatus ...");
+
+  if (DEBUG) return;
+
+  byte sd = stash.create();
+
+  //const char s_error[]  = "%7B%22state%22%3A%7B%22open%22%3Anull%7D%7D";
+  //const char s_open[]  = "%7B%22state%22%3A%7B%22open%22%3Atrue%7D%7D";
+  //const char s_close[] = "%7B%22state%22%3A%7B%22open%22%3Afalse%7D%7D";
+  stash.print("key=");
+  stash.print(TOKEN);
+  //stash.print("&sensors=");
+  //stash.println(isOpen == DOOR_OPEN ? s_open : (isOpen == DOOR_CLOSED ? s_close : s_error));
+  stash.print("&door=");
+  stash.println(isOpen == DOOR_OPEN ? "true" : (isOpen == DOOR_CLOSED ? "false" : "null"));
   stash.save();
   int stash_size = stash.size();

@@ -44,44 +110,134 @@
   Serial.println("[>] Done sending doorstatus!");
 }

+void findTempSensor() {
+  while (numberOfDevices < 1) {
+    // Grab a count of devices on the wire
+    numberOfDevices = sensors.getDeviceCount();
+
+    // locate devices on the bus
+    Serial.print("[T] Locating one-wire devices on port ");
+    Serial.println(PIN_ONEWIRE);
+
+    Serial.print("[T] Found ");
+    Serial.print(numberOfDevices, DEC);
+    Serial.println(" one-wire devices.");
+
+    // report parasite power requirements
+    Serial.print("[T] Parasite power is: ");
+    if (sensors.isParasitePowerMode()) Serial.println("ON");
+    else Serial.println("OFF");
+
+    if (numberOfDevices < 1) delay(500);
+  }
+  // Loop through each device, print out address
+  for (int i = 0; i < numberOfDevices; i++)
+  {
+    if (sensors.getAddress(tempDeviceAddress, i))
+    {
+      Serial.print("[T] Found device ");
+      Serial.println(i, DEC);
+      sensors.setResolution(tempDeviceAddress, TEMPERATURE_PRECISION);
+    } else
+    {
+      Serial.print("[T] Found ghost device at ");
+      Serial.print(i, DEC);
+      Serial.print(" but could not detect address. Check power and cabling");
+    }
+  }
+}
+
+static void sendToTwitter () {
+  Serial.println("Sending tweet...");
+  byte sd = stash.create();
+
+  const char tweet[] = "@solarkennedy the test Twitter sketch works!";
+  stash.print("token=");
+  stash.print(TOKEN);
+  stash.print("&status=");
+  stash.println(tweet);
+  stash.save();
+  int stash_size = stash.size();
+
+  // Compose the http POST request, taking the headers below and appending
+  // previously created stash in the sd holder.
+  Stash::prepare(PSTR("POST http://$F/update HTTP/1.0" "\r\n"
+    "Host: $F" "\r\n"
+    "Content-Length: $D" "\r\n"
+    "\r\n"
+    "$H"),
+  api, api, stash_size, sd);
+
+  // send the packet - this also releases all stash buffers once done
+  // Save the session ID so we can watch for it in the main loop.
+  session = ether.tcpSend();
+}
+
 void setup () {
+  // Setup Serial:
   Serial.begin(BAUDRATE);
   Serial.println("\n[Stefan's SpaceAPI Publisher]");

-  if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
-    Serial.println(F("Failed to access Ethernet controller"));
-  if (!ether.dhcpSetup())
-    Serial.println(F("[*] DHCP failed"));
-
-  ether.printIp("[*] IP:  ", ether.myip);
-  ether.printIp("[*] GW:  ", ether.gwip);
-  ether.printIp("[*] DNS: ", ether.dnsip);
-
-  if (!ether.dnsLookup(api))
-    Serial.println(F("[*] DNS failed"));
-
-  ether.printIp("[*] SRV: ", ether.hisip);
-
-  updateDoorstatus(oldDoorstatus);
+  // Setup temp sensor:
+  sensors.begin();
+  findTempSensor();
+
+  // Setup network:
+  if (!DEBUG)
+  {
+    if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
+      Serial.println(F("[N] Failed to access Ethernet controller"));
+    if (!ether.dhcpSetup())
+      Serial.println(F("[N] DHCP failed"));
+
+    ether.printIp("[N] IP:  ", ether.myip);
+    ether.printIp("[N] GW:  ", ether.gwip);
+    ether.printIp("[N] DNS: ", ether.dnsip);
+
+    if (!ether.dnsLookup(api))
+      Serial.println(F("[N] DNS failed"));
+
+    ether.printIp("[N] SRV: ", ether.hisip);
+  }
+  sendToTwitter();
+}
+
+float getTemp() {
+  sensors.requestTemperatures();
+  sensors.getAddress(tempDeviceAddress, 0);
+  float temp = sensors.getTempC(tempDeviceAddress);
+  return temp;
 }

 void loop () {
+  ether.packetLoop(ether.packetReceive());

   // TODO: check doorsensor
-  bool newDoorstatus = false;
-
-  if(newDoorstatus != oldDoorstatus) {
-    Serial.println(newDoorstatus ? "[!] DOOR OPENED!" : "[!] DOOR CLOSED!");
+  int newDoorstatus = DOOR_ERROR;
+  float newTemp = getTemp();
+
+  if (newDoorstatus != oldDoorstatus) {
+    Serial.println(newDoorstatus == DOOR_OPEN ? "[!] DOOR OPENED!" : "[!] DOOR CLOSED!");
     updateDoorstatus(newDoorstatus);
     oldDoorstatus = newDoorstatus;
-  }
-
-  // HTTP response handling (mostly for debug):
-  ether.packetLoop(ether.packetReceive());
-  const char* reply = ether.tcpReply(session);
-  if (reply != 0) {
-    Serial.println("[<] Got a response:");
-    Serial.println(reply);
-  }
-}
-
+
+  } else if (newTemp != oldTemp) { // comparing floats? well ...
+    Serial.print("[!] Temp updated: ");
+    Serial.println(newTemp);
+    updateTemperature(newTemp);
+    //oldTemp = newTemp;
+  } else Serial.println("[*] Nothing to do.");
+
+  // HTTP response handling (mostly for debug)
+  // (this may need all your dynamic memory)
+
+  //  const char* reply = ether.tcpReply(session);
+  //  if (reply != 0) {
+  //    Serial.println("[<] Got a response:");
+  //    Serial.println(reply);
+  //  }
+
+  delay(5000);
+
+}
+


Update ecran debug Séparation des menus de debug

--- Ecran/BotMenu/BotMenu.ino
+++ Ecran/BotMenu/BotMenu.ino
@@ -336,15 +336,25 @@

 M2_BUTTON(el_debug_update, "f4", "MAJ", fn_debug_update);

-M2_LIST(num_list_debug) = {
+M2_LIST(num_list_debug_01) = {
     &el_num_label_debug_01, &el_num_debug_01, &el_num_label_debug_02, &el_num_debug_02,
     &el_num_label_debug_01, &el_num_debug_01, &el_num_label_debug_02, &el_num_debug_02,
     &el_num_label_debug_01, &el_num_debug_01, &el_num_label_debug_02, &el_num_debug_02,
     &el_num_goto_top, &el_debug_update
 };

-M2_GRIDLIST(el_num_list_debug, "c4", num_list_debug);
-M2_ALIGN(el_top_num_menu_debug, "-1|1W64H64", &el_num_list_debug);
+M2_GRIDLIST(el_num_list_debug_01, "c4", num_list_debug_01);
+M2_ALIGN(el_top_num_menu_debug_01, "-1|1W64H64", &el_num_list_debug_01);
+
+M2_LIST(num_list_debug_02) = {
+    &el_num_label_debug_01, &el_num_debug_01, &el_num_label_debug_02, &el_num_debug_02,
+    &el_num_label_debug_01, &el_num_debug_01, &el_num_label_debug_02, &el_num_debug_02,
+    &el_num_label_debug_01, &el_num_debug_01, &el_num_label_debug_02, &el_num_debug_02,
+    &el_num_goto_top, &el_debug_update
+};
+
+M2_GRIDLIST(el_num_list_debug_02, "c4", num_list_debug_02);
+M2_ALIGN(el_top_num_menu_debug_02, "-1|1W64H64", &el_num_list_debug_02);

 //____________________________________________________________________________________________________
@@ -425,8 +435,8 @@
   { ". Test Moteur", &top_el_muse},
   //{ ". File Select", &el_top_fs },
   { "Debug ", NULL },
-  { ". Debug Moteur", &el_top_num_menu_debug},
-  { ". Debug Autre", &el_top_num_menu_debug},
+  { ". Debug Moteur", &el_top_num_menu_debug_01},
+  { ". Debug Autre", &el_top_num_menu_debug_02},
   { "Top", &top_el_expandable_menu },
   { NULL, NULL },
 };


run, tron, troff

run, tron, troff

--- src/BLuB.ino
+++ src/BLuB.ino
@@ -8,8 +8,9 @@
 // Version history
 //
 // v0.01  2013-June-19  Line entry, line editing
-//			cmds: help, mem, new, list
-//			      EEPROM: elist, eload, esave, enew
+//			cmds: 	help, mem, new, list
+//			      	EEPROM: elist, eload, esave, enew
+//				run, tron, troff
 //
 // v0.00  2013-June-18  Initial test versions

@@ -40,6 +41,40 @@
 int ramFree = 0;
 int eeFree = 0;

+bool trace = false;
+
+////////////////////////////////////////////////////////////////////////////////
+
+#define kBufLen (16)
+char buffer[kBufLen];
+
+int latoi( char * buf )
+{
+	int v = 0;
+	// find the integer starting at buf[0]
+	while( *buf <= '9' && *buf >= '0' && v<kBufLen  ) {
+		buffer[v++] = *buf;
+		*buf++;
+	}
+	if( v == 0 ) {
+		// no number!
+		return -1;
+	}
+
+	buffer[v] = '\0';
+
+	// my atoi (save on library overhead)
+	v = 0;
+	buf = buffer;
+	while( *buf ) {
+		v *= 10;
+		v += (*buf)-'0';
+		buf++;
+	}
+	return v;
+}
+
+////////////////////////////////////////////////////////////////////////////////

 void cmd_mem( void )
 {
@@ -81,7 +116,8 @@
 	Serial.println( "" );
 	Serial.println( "Available commands:" );
 	//                   ------- ------- ------- ------- -------
-	Serial.println( "    help    mem     new     list    run" );
+	Serial.println( "    help    mem     new     list" );
+	Serial.println( "    run     tron    troff" );
 	Serial.println( "    elist   eload   esave   enew" );
 	//                   ------- ------- ------- ------- -------
 }
@@ -216,9 +252,92 @@
 	// no need for println, since program ram ends with newline
 }

+
+////////////////////////////////////////////////////////////////////////////////
+
+void cmd_tron( void )
+{
+	trace = true;
+	Serial.println( "Trace on." );
+}
+
+void cmd_troff( void )
+{
+	trace = false;
+	Serial.println( "Trace off." );
+}
+
+char * findLine( int line )
+{
+	char *bufc = programRam;
+	int cline = latoi( bufc );
+
+	while( cline != line && *bufc != '\0' ) {
+		// skip to next line
+		while( *bufc != '\0' && *bufc != '\n' ) bufc++;
+		// fill cline
+		bufc++;
+		cline = latoi( bufc );
+	}
+
+	return bufc;
+}
+
 void cmd_run( void )
 {
-	Serial.println( "Not yet." );
+	int cline = 0;
+	int next = -1;
+	char *bufc = programRam;
+
+	if( *bufc == '\0' ) return;
+
+	while( *bufc ) {
+		// determine the next line number
+		if( next == -1 ) {
+			// starting, use the first one.
+			bufc = programRam;
+
+		} else if( next == -2 ) {
+			// use the next one.
+			while( *bufc != '\0' && *bufc != '\n' ) bufc++;
+			bufc++;
+
+		} else {
+			// next contains the next line to execute
+			// find the line
+			bufc = findLine( next );
+			if( *bufc == '\0' ) {
+				Serial.print( (long) next, DEC );
+				Serial.println( ": Line not found." );
+				break;
+			}
+		}
+
+		next = -2; // set for next line
+
+		if( *bufc == '\0' ) {
+			// just in case.
+			break;
+		}
+
+		cline = latoi( bufc );
+		if( trace ) {
+			Serial.print( "Line: " );
+			char * tc = bufc;
+			while( (*tc) != '\0' && (*tc) != '\n' ) {
+				Serial.write( tc, 1 );
+				tc++;
+			}
+			Serial.println( "" );
+
+			// get user input (return)
+			while( !Serial.available() );
+			(void) Serial.read();
+		}
+	}
+
+	Serial.print( "Stopped at line " );
+	Serial.println( (long)cline, DEC );
 }

 ////////////////////////////////////////////////////////////////////////////////
@@ -238,35 +357,7 @@
 	cmd_mem();
 }

-#define kBufLen (16)
-char buffer[16];
-
-
-int latoi( char * buf )
-{
-	int v = 0;
-	// find the integer starting at buf[0]
-	while( *buf <= '9' && *buf >= '0' && v<kBufLen  ) {
-		buffer[v++] = *buf;
-		*buf++;
-	}
-	if( v == 0 ) {
-		// no number!
-		return -1;
-	}
-
-	buffer[v] = '\0';
-
-	// my atoi (save on library overhead)
-	v = 0;
-	buf = buffer;
-	while( *buf ) {
-		v *= 10;
-		v += (*buf)-'0';
-		buf++;
-	}
-	return v;
-}
+

 void cmd_removeLine( int lineNo, bool verbose )
@@ -402,6 +493,8 @@
 	else if( !strcmp( linebuf, "eload" )) { cmd_eload(); }
 	else if( !strcmp( linebuf, "esave" )) { cmd_esave(); }

+	else if( !strcmp( linebuf, "tron" )) { cmd_tron(); }
+	else if( !strcmp( linebuf, "troff" )) { cmd_troff(); }
 	else if( !strcmp( linebuf, "run" )) { cmd_run(); }

 	else if( linebuf[0] >= '0' && linebuf[0] <= '9' ) {


reader

reader

--- motor_pump/motor_pump.ino
+++ motor_pump/motor_pump.ino
@@ -1,19 +1,34 @@
-const int switchPin =2
-const int motorPin =9
-int switchstate =0
+const int switchPin =2;
+const int motorPin =9;
+int switchstate = 0;
+const int Input = 12;
+int moistoure = 0;
+//int ByteRecieved;

 void setup() {
   pinMode(motorPin, OUTPUT);
-  pinMode(switchpin, INPUT);
-}
+  pinMode(switchPin, INPUT);
+  pinMode (Input, INPUT);
+//  Serial.begin(9600);
+//  Serial.println(digitalRead(Input));
+}

-void loop() {
-  switchstate = digitalRead(switchPin);
-
-  if (switchstate == HIGH) {
+void loop(){
+moistoure = digitalRead(Input);
+switchstate = digitalRead(switchPin);
+
+  if (moistoure >85) {
     digitalWrite(motorPin, HIGH);
   }
   else{
-    digitalWrite(motorPin,LOW)
+    digitalWrite(motorPin,LOW);
   }
+
+
+//  if(Serial.available()>0){
+    //ByteRecieved = Serial.read();
+//    Serial.println(moistoure);
+//  }
+
 }
+


bug fixed for the GPS

bug fixed for the GPS

--- mwsLRWHFv2/mwsLRWHFv2.ino
+++ mwsLRWHFv2/mwsLRWHFv2.ino
@@ -84,7 +84,7 @@
 //For Arduino Uno
 //static const int RXPin = 5, TXPin = 4; //GPS is attached to pin 4(TX from GPS) and pin 5(RX into GPS)
 //For Arduino Mega
-static const int RXPin = 6, TXPin = 7; //GPS is attached to pin 7(TX from GPS) and pin 6(RX into GPS)
+static const int RXPin = 50, TXPin = 51; //GPS is attached to pin 7(TX from GPS) and pin 6(RX into GPS)
 SoftwareSerial ss(RXPin, TXPin);

 MPL3115A2 myPressure; //Create an instance of the pressure sensor
@@ -93,20 +93,18 @@
 //Hardware pin definitions
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 // digital I/O pins
+const byte RAIN = 2;
 const byte WSPEED = 3;
-const byte RAIN = 2;
-const byte STAT1 = 7;
+const byte GPS_PWRCTL = 6; //Pulling this pin low puts GPS to sleep but maintains RTC and RAM
+//For Arduino Uno Only
+//const byte STAT1 = 7;
 const byte STAT2 = 8;
-//For Arduino Uno
-//const byte GPS_PWRCTL = 6; //Pulling this pin low puts GPS to sleep but maintains RTC and RAM
-//For Arduino Mega
-const byte GPS_PWRCTL = 5; //Pulling this pin low puts GPS to sleep but maintains RTC and RAM

 // analog I/O pins
-const byte REFERENCE_3V3 = A3;
+const byte WDIR = A0;
 const byte LIGHT = A1;
 const byte BATT = A2;
-const byte WDIR = A0;
+const byte REFERENCE_3V3 = A3;
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

 //Global Variables
@@ -182,7 +180,7 @@

     rainlast = raintime; // set up for next event
   }
-
+
   //Rain or not (1 or 0)
   if(rainin >0)
   {
@@ -191,12 +189,12 @@
   }
   if(rainin ==0)
   {
-   Rainindi=0;
-   Rainindlast = millis();
-   Rainindlast = Rainindtime;
+    Rainindi=0;
+    Rainindlast = millis();
+    Rainindlast = Rainindtime;
   }
   Rainindinter = Rainindlast - Rainindtime;
-
+
 }

 void wspeedIRQ()
@@ -207,32 +205,37 @@
     lastWindIRQ = millis(); //Grab the current time
     windClicks++; //There is 1.492MPH for each click per second.
   }
-
+
 }

 void setup()
 {
+  //Switch on the GPS
+  pinMode(GPS_PWRCTL, OUTPUT);
+  digitalWrite(GPS_PWRCTL, HIGH); //Pulling this pin low puts GPS to sleep but maintains RTC and RAM
+
+  //Start Serial port reporting
   Serial.begin(9600);
-
+
   // set up the LCD's number of columns and rows:
   lcd.begin(16, 2);
   lcd.backlight();
-
-  ss.begin(9600); //Begin listening to GPS over software serial at 9600. This should be the default baud of the module.
+
+  //Start software serial for GPS
+  //Begin listening to GPS over software serial at 9600. This should be the default baud of the module.
+  ss.begin(9600);
   Serial.print(F("lon,lat,altitude,sats,date,GMTtime,winddir"));
   Serial.print(F(",windspeedms,windgustms,windgustdir,windspdms_avg2m,winddir_avg2m,windgustms_10m,windgustdir_10m"));
   Serial.print(F(",humidity,tempc,rainhourmm,raindailymm,rainindicate,rainduration,pressure,batt_lvl,light_lvl"));

-  pinMode(STAT1, OUTPUT); //Status LED Blue
+  //For Arduino UNO Only
+  //pinMode(STAT1, OUTPUT); //Status LED Blue
   pinMode(STAT2, OUTPUT); //Status LED Green
-
-  pinMode(GPS_PWRCTL, OUTPUT);
-  digitalWrite(GPS_PWRCTL, HIGH); //Pulling this pin low puts GPS to sleep but maintains RTC and RAM
-
+
   pinMode(WSPEED, INPUT_PULLUP); // input from wind meters windspeed sensor
   pinMode(RAIN, INPUT_PULLUP); // input from wind meters rain gauge sensor
-
+
   pinMode(REFERENCE_3V3, INPUT);
   pinMode(LIGHT, INPUT);

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

-  //Configure the humidity sensor
+    //Configure the humidity sensor
   myHumidity.begin();

   seconds = 0;
@@ -254,17 +257,22 @@

   // turn on interrupts
   interrupts();
-  digitalWrite(STAT1, HIGH); //Blink stat LED 1 second
+  digitalWrite(STAT2, HIGH); //Blink stat LED 1 second
   delay(1000);
-  digitalWrite(STAT1, LOW); //Blink stat LED
-  smartdelay(60000); //Wait 60 seconds, and gather GPS data
+  digitalWrite(STAT2, LOW); //Blink stat LED
+  smartdelay(30000); //Wait 60 seconds, and gather GPS data
+  Serial.println("");
+  Serial.print("LAT=");  Serial.println(gps.location.lat(), 6);
+  Serial.print("LONG="); Serial.println(gps.location.lng(), 6);
+  Serial.print("TIME="); Serial.print(gps.time.hour(), 6);
+  Serial.print(":");Serial.println(gps.time.minute(), 6);
   minutes = gps.time.minute();
   minutes_10m = gps.time.minute();
   seconds = gps.time.second();
   lastSecond = millis();
-  digitalWrite(STAT1, HIGH); //Blink stat LED 1 second
+  digitalWrite(STAT2, HIGH); //Blink stat LED 1 second
   delay(1000);
-  digitalWrite(STAT1, LOW); //Blink stat LED
+  digitalWrite(STAT2, LOW); //Blink stat LED
   lcd.print("Weather Station online!");

 }
@@ -274,8 +282,8 @@
   //Keep track of which minute it is
   if(millis() - lastSecond >= 1000)
   {
-    digitalWrite(STAT1, HIGH); //Blink stat LED
-
+    digitalWrite(STAT2, HIGH); //Blink stat LED
+
     lastSecond += 1000;

     //Take a speed and direction reading every second for 2 minute average
@@ -302,7 +310,7 @@
       windgustms = currentSpeed;
       windgustdir = currentDirection;
     }
-
+
     if(++seconds > 59)
     {
       seconds = 0;
@@ -317,7 +325,7 @@
     //Report all readings every second
     printWeather();

-    digitalWrite(STAT1, LOW); //Turn off stat LED
+    digitalWrite(STAT2, LOW); //Turn off stat LED
   }

   smartdelay(800); //Wait 1 second, and gather GPS data
@@ -331,7 +339,8 @@
   {
     while (ss.available())
       gps.encode(ss.read());
-  } while (millis() - start < ms);
+  }
+  while (millis() - start < ms);
 }

@@ -406,7 +415,7 @@

   //Calc battery level
   batt_lvl = get_battery_level();
-
+
 }

 //Returns the voltage of the light sensor based on the 3.3V rail
@@ -416,11 +425,11 @@
   float operatingVoltage = analogRead(REFERENCE_3V3);

   float lightSensor = analogRead(LIGHT);
-
+
   operatingVoltage = 3.3 / operatingVoltage; //The reference voltage is 3.3V
-
+
   lightSensor = operatingVoltage * lightSensor;
-
+
   return(lightSensor);
 }

@@ -433,13 +442,13 @@
   float operatingVoltage = analogRead(REFERENCE_3V3);

   float rawVoltage = analogRead(BATT);
-
+
   operatingVoltage = 3.30 / operatingVoltage; //The reference voltage is 3.3V
-
+
   rawVoltage = operatingVoltage * rawVoltage; //Convert the 0 to 1023 int to actual voltage on BATT pin
-
+
   rawVoltage *= 4.90; //(3.9k+1k)/1k - multiple BATT voltage by the voltage divider to get actual system voltage
-
+
   return(rawVoltage);
 }

@@ -576,7 +585,7 @@
   lcd.print(F("Lat:"));
   lcd.print(gps.location.lat(), 6);
   delay(5000);
-
+
   lcd.clear();
   sprintf(sz, "%02d-%02d-%02d", gps.date.year(), gps.date.month(), gps.date.day());
   lcd.print(sz);
@@ -585,7 +594,7 @@
   lcd.print(sz);
   lcd.print(F(" GMT"));
   delay(5000);
-
+
   lcd.clear();
   lcd.print(F("WD: "));
   lcd.print(get_wind_direction());
@@ -595,7 +604,7 @@
   lcd.print(get_wind_speed(), 1);
   lcd.print(F(" m/s"));
   delay(5000);
-
+
   lcd.clear();
   lcd.print(F("H:"));
   lcd.print(myHumidity.readHumidity(),2);
@@ -605,7 +614,7 @@
   lcd.print(myPressure.readTemp(),2);
   lcd.print(F(" C"));
   delay(5000);
-
+
   lcd.clear();
   lcd.print("R:");
   lcd.print(dailyrainin);
@@ -629,3 +638,4 @@
 }

+


Add display messages for setup status

Add display messages for setup status

--- payload/payload.ino
+++ payload/payload.ino
@@ -28,15 +28,29 @@
   // Illuminate LED.
   pinMode(13, OUTPUT);
   digitalWrite(13, HIGH);
+
+  // Give time to open serial monitor.
+  delay(2000);

-  // Start serial communication.
+  // Start serial communication.
   Serial.begin(9600); // bits/second does not matter for Teensy 3.6
-  Serial.println("In setup.");
-
-  // Setup the custom data structures.
+  Serial.print("In setup");
+  delay(512);
+  Serial.print(".");
+  delay(512);
+  Serial.print(".");
+  delay(512);
+  Serial.println(".");
+  Serial.println();
+
+  // Setup() the custom data structures.
   for (custom::Setupable* obj : setupables) {
     obj->Setup();
   }
+
+  Serial.println();
+  Serial.println("SETUP COMPLETE.");
+  Serial.println();
 }

 void printBmpData(void) {


Rearange the code a bit.

Rearange the code a bit.

--- MorseCodeDecoder.ino
+++ MorseCodeDecoder.ino
@@ -19,37 +19,14 @@
 unsigned long currentHold = 0; //the length of time of the current button press in milliseconds
 unsigned long previousHold = 0; //the length of time of the previous button press in milliseconds

+int determineDotDash(unsigned long holdMillis);
+String getDotDashString(int input);
+
 void setup() {
   pinMode(LED, OUTPUT);
   pinMode(BUTTON, INPUT_PULLUP);

   Serial.begin(9600);
-}
-
-/**
- * Given the length of a button press in milliseconds, return DOT, DASH, or NOTHING
- */
-int determineDotDash(unsigned long holdMillis) {
-  int toReturn = NOTHING;
-  if (previousHold >= dashMillisMin) {
-    toReturn = DASH;
-  } else if (previousHold >= dotMillisMin) {
-    toReturn = DOT;
-  }
-  return toReturn;
-}
-
-/**
- * Given DOT, DASH, or NOTHING, return a string representing it
- */
-String getDotDashString(int input) {
-  String toReturn = "nothing";
-  if (input == DOT) {
-    toReturn = "dot";
-  } else if (input == DASH) {
-    toReturn = "dash";
-  }
-  return toReturn;
 }

 void loop() {
@@ -82,5 +59,29 @@
   previousHold = currentHold;
 }

+/**
+ * Given the length of a button press in milliseconds, return DOT, DASH, or NOTHING
+ */
+int determineDotDash(unsigned long holdMillis) {
+  int toReturn = NOTHING;
+  if (previousHold >= dashMillisMin) {
+    toReturn = DASH;
+  } else if (previousHold >= dotMillisMin) {
+    toReturn = DOT;
+  }
+  return toReturn;
+}

+/**
+ * Given DOT, DASH, or NOTHING, return a string representing it
+ */
+String getDotDashString(int input) {
+  String toReturn = "nothing";
+  if (input == DOT) {
+    toReturn = "dot";
+  } else if (input == DASH) {
+    toReturn = "dash";
+  }
+  return toReturn;
+}


Rename HX711 instance

Rename HX711 instance

--- coffee-scale.ino
+++ coffee-scale.ino
@@ -7,19 +7,18 @@
 #define DISP_TIMER_DIO 3
 #define DISP_SCALE_CLK 8
 #define DISP_SCALE_DIO 9
-#define SCALE_DT       A2
-#define SCALE_SCK      A1

 #define FILTER_SIZE 10
 #define HYSTERESIS_SIZE 0.1

+#define LOAD_CELL_DT A2
+#define LOAD_CELL_SCK A1
 #define SCALE_FACTOR 1874
-#define SCALE_OFFSET 984550
 #define TARE_AVERAGES 10

 TimerDisplay    timerDisplay(DISP_TIMER_CLK, DISP_TIMER_DIO);
 GramsDisplay    gramsDisplay(DISP_SCALE_CLK, DISP_SCALE_DIO);
-HX711           scale;
+HX711 loadCell(LOAD_CELL_DT, LOAD_CELL_SCK);
 SmoothingFilter filter(FILTER_SIZE, HYSTERESIS_SIZE);

@@ -28,16 +27,14 @@
   // Serial comm
   Serial.begin(38400);

-  // Load cell
-  scale.begin(SCALE_DT, SCALE_SCK);
-  scale.set_scale(SCALE_FACTOR);
-  scale.tare(TARE_AVERAGES);
+  loadCell.set_scale(SCALE_FACTOR);
+  loadCell.tare(TARE_AVERAGES);
 }

 void loop()
 {
-  filter.addValue(scale.get_units());
+  filter.addValue(loadCell.get_units());
   float weight_in_grams = filter.getValue();

   gramsDisplay.displayGrams(weight_in_grams);


Salt Lamp v1.3

Salt Lamp v1.3

--- sketch.ino
+++ sketch.ino
@@ -3,7 +3,7 @@
 // By Chris Barrett - Polaris Interplanetary - Special Projects Division
 // Supports two modes; All pixel colour fade, and 8 pixel RGB mixer. All modes are asynchronous, and compartmentalized into functions.
 // January 2016 - Shimmer has been overhauled. Cleaner, faster and more productive. NO MORE MID FADE FLICKER!
-//              - Still needs collision detection.
+//              - Collision detection has been implemented, not sure if it works, will need to check further.

 #include <Adafruit_NeoPixel.h>
 #include <avr/power.h>
@@ -14,7 +14,7 @@

 // what address are the pixels going to range? This was helpful in prototyping because I could use a long strip of lights and only address the last few and stick them in the salt crystal.
 #define NUMPIXELS      133
-#define LOWPIXELS      83
+#define LOWPIXELS      90

@@ -57,6 +57,7 @@
 int pixpos;                                         // array to store the pixel brightness for each possible pixel
 int firstrun = 0;                                   //array to write first run values to pixels
 int shimspd[8];                                    //array to set random speed value for shimmer
+int pixchck[8];

 void setup() {                                      //-----------------------------------------------(Setup)
     pinMode(butpin, INPUT);                         // Set buttonpin as input
@@ -88,13 +89,13 @@
       shimmer();
   }

-  //Serial.println(pixupdn[1]);
+
   pixels.show();                                  // This sends the updated pixel color to the hardware.

-  delay(40);
+  delay(30);

 }

@@ -231,6 +232,28 @@
             pixcoldic[i] = random(0,9);             //Creates a magic number
             pixelgo[i] = 1;                         //Activates a pixel for draw
             shimspd[i] = random(1,5);
+
+            while (pixchck[i] == 0){                //collision detection
+              pixmat[i] == 0;
+              randomSeed(analogRead(0));
+              pixelvalue[i] = random(LOWPIXELS,NUMPIXELS);
+              //Serial.println("repositioning");
+              //Serial.println(i);
+
+              for (int b=0; b <= 7; b++){                      //For loop to write initial random position
+                if (pixelvalue[i] == pixelvalue[b]){
+                  pixmat[i] = pixmat[i] + 1;
+                }
+
+                if (pixmat[i] <= 1){
+                  pixchck[i] = 1;
+                }
+              }
+
+
+            }
+
+
         }
     }

@@ -252,7 +275,7 @@

 }

-void drawPixel(int pixelv,int coldic, int rate){              //-----------------------------------------------(Red Pixel Draw Function)
+void drawPixel(int pixelv,int coldic, int rate){              //-----------------------------------------------(Pixel Draw Function)

@@ -287,6 +310,7 @@
         pixelvalue[pixelv] = random(LOWPIXELS,NUMPIXELS);                 //create new random pixel location
         pixelgo[pixelv] = 0;                                              //deactivate pixel activate bit
         pixupdn[pixelv] = 0;                                              //reset counter
+        pixchck[pixelv] = 0;
       }

 }


Close #17

Close #17

--- DigitalVFO.ino
+++ DigitalVFO.ino
@@ -2219,16 +2219,20 @@
     switch (event)
     {
       case vfo_RLeft:
+        if (VfoFrequency <= MinFreq)
+          break;
         VfoFrequency -= offset2bump[VfoSelectDigit];
         if (VfoFrequency < MinFreq)
           VfoFrequency = MinFreq;
-        if (VfoFrequency > MaxFreq)
-          VfoFrequency = MaxFreq;
+//        if (VfoFrequency > MaxFreq)
+//          VfoFrequency = MaxFreq;
        break;
       case vfo_RRight:
+        if (VfoFrequency >= MaxFreq)
+          break;
         VfoFrequency += offset2bump[VfoSelectDigit];
-        if (VfoFrequency < MinFreq)
-          VfoFrequency = MinFreq;
+//        if (VfoFrequency < MinFreq)
+//          VfoFrequency = MinFreq;
         if (VfoFrequency > MaxFreq)
           VfoFrequency = MaxFreq;
         break;


Modified frequency display to use commas

--- DigitalVFO.ino
+++ DigitalVFO.ino
@@ -46,13 +46,13 @@

 // Digital VFO program name & version
 const char *ProgramName = "DigitalVFO";
-const char *Version = "1.6";
-const char *MinorVersion = ".3";
+const char *Version = "1.7";
+const char *MinorVersion = ".0";
 const char *Callsign = "ac3dn";

 // display constants - below is for ubiquitous small HD44780 16x2 display
-const int NumRows = 2;
-const int NumCols = 16;
+const int LcdNumRows = 2;
+const int LcdNumCols = 16;

 //-----
 // Some convenience typedefs
@@ -311,6 +311,25 @@
 byte *BatterySymbol = battunder;

 //##############################################################################
+// RE internal variables.
+//##############################################################################
+
+// internal variables
+UINT ReHoldClickTime = DefaultHoldClickTime;
+UINT ReDClickTime = DefaultDClickTime;
+
+bool re_rotation = false;     // true if rotation occurred while knob down
+bool re_down = false;         // true while knob is down
+ULONG re_down_time = 0;       // milliseconds when knob is pressed down
+ULONG last_click = 0;         // time when last single click was found
+
+// expecting rising edge on pinA - at detent
+volatile byte aFlag = 0;
+
+// expecting rising edge on pinA - at detent
+volatile byte bFlag = 0;
+
+//##############################################################################
 // Utility routines
 //##############################################################################

@@ -378,12 +397,12 @@
 // Abort the program.
 // Tries to tell the world what went wrong.
 //     msg  address of error string
-// Only first NumRows*NumCols chars of message is displayed on LCD.
+// Only first LcdNumRows*LcdNumCols chars of message is displayed on LCD.
 //----------------------------------------

 void DV_abort(const char *msg)
 {
-  char buf[NumCols*NumRows+1];
+  char buf[LcdNumCols*LcdNumRows+1];
   char *ptr = buf;

   Aborted = true;   // set "Aborted" flag
@@ -391,22 +410,22 @@
   // print error on console (maybe)
   Serial.printf("message=%s\nTeensy is aborted!\n", msg);

-  // truncate/pad message to NumRows * NumCols chars
-  for (int i = 0; i < NumCols*NumRows; ++i)
+  // truncate/pad message to LcdNumRows * LcdNumCols chars
+  for (int i = 0; i < LcdNumCols*LcdNumRows; ++i)
     *ptr++ = ' ';
   *ptr = '\0';

-  strncpy(buf, msg, NumCols*NumRows);
-  if (strlen(msg) < NumCols*NumRows)
+  strncpy(buf, msg, LcdNumCols*LcdNumRows);
+  if (strlen(msg) < LcdNumCols*LcdNumRows)
     strncpy(buf + strlen(msg), "                                ",
-            NumCols*NumRows - strlen(msg));
+            LcdNumCols*LcdNumRows - strlen(msg));

   // show what we can on the display
   lcd.clear();
-  for (int i = 0; i < NumRows; ++i)
+  for (int i = 0; i < LcdNumRows; ++i)
   {
     lcd.setCursor(0, i);
-    lcd.print(buf + i*NumCols);
+    lcd.print(buf + i*LcdNumCols);
   }
 }

@@ -482,7 +501,7 @@
   {
     lcd.print(MinorVersion);
   }
-  lcd.setCursor(NumCols-strlen(Callsign), 1);
+  lcd.setCursor(LcdNumCols-strlen(Callsign), 1);
   lcd.print(Callsign);
 }

@@ -572,6 +591,240 @@
     ++str;
   }
 }
+
+//##############################################################################
+// Code to save/restore in EEPROM.
+//##############################################################################
+
+//----------------------------------------
+// Save VFO state to EEPROM.
+// Everything except slot data.
+//----------------------------------------
+
+void save_to_eeprom(void)
+{
+  EEPROM.put(EepromFreq, VfoFrequency);
+  EEPROM.put(EepromSelDigit, VfoSelectDigit);
+  EEPROM.put(EepromVfoClockOffset, VfoClockOffset);
+  EEPROM.put(EepromBrightness, LcdBrightness);
+  EEPROM.put(EepromContrast, LcdContrast);
+  EEPROM.put(EepromHoldClickTime, ReHoldClickTime);
+  EEPROM.put(EepromDClickTime, ReDClickTime);
+  EEPROM.put(EepromVoltsCalibrate, VoltsCalibrate);
+}
+
+//----------------------------------------
+// Restore VFO state from EEPROM.
+// Everything except slot data.
+//----------------------------------------
+
+void restore_from_eeprom(void)
+{
+  EEPROM.get(EepromFreq, VfoFrequency);
+  EEPROM.get(EepromSelDigit, VfoSelectDigit);
+  EEPROM.get(EepromVfoClockOffset, VfoClockOffset);
+  EEPROM.get(EepromBrightness, LcdBrightness);
+  EEPROM.get(EepromContrast, LcdContrast);
+  EEPROM.get(EepromHoldClickTime, ReHoldClickTime);
+  EEPROM.get(EepromDClickTime, ReDClickTime);
+  EEPROM.get(EepromVoltsCalibrate, VoltsCalibrate);
+}
+
+//----------------------------------------
+// Given slot number, return freq/offset.
+//     freq    pointer to Frequency item to be updated
+//     offset  pointer to selection offset item to be updated
+//----------------------------------------
+
+void get_slot(int slot_num, Frequency &freq, SelOffset &offset)
+{
+  int freq_address = EepromSaveFreqBase + slot_num * sizeof(Frequency);
+  int offset_address = EepromSaveOffsetBase + slot_num * sizeof(SelOffset);
+
+  EEPROM.get(freq_address, freq);
+  EEPROM.get(offset_address, offset);
+}
+
+//----------------------------------------
+// Put frequency/offset into given slot number.
+//     freq    pointer to Frequency item to be saved in slot
+//     offset  pointer to selection offset item to be saved in slot
+//----------------------------------------
+
+void put_slot(int slot_num, Frequency freq, SelOffset offset)
+{
+  int freq_address = EepromSaveFreqBase + slot_num * sizeof(Frequency);
+  int offset_address = EepromSaveOffsetBase + slot_num * sizeof(SelOffset);
+
+  EEPROM.put(freq_address, freq);
+  EEPROM.put(offset_address, offset);
+}
+
+//----------------------------------------
+// Print all EEPROM saved data to console.
+//----------------------------------------
+
+#define DELAY_MS 100  // not sure why we need a delay to print reliably
+
+void dump_eeprom(void)
+{
+  Frequency freq;
+  SelOffset offset;
+  int clkoffset;
+  int brightness;
+  int contrast;
+  UINT hold;
+  UINT dclick;
+  UINT volt_calib;
+
+  EEPROM.get(EepromFreq, freq);
+  EEPROM.get(EepromSelDigit, offset);
+  EEPROM.get(EepromVfoClockOffset, clkoffset);
+  EEPROM.get(EepromContrast, contrast);
+  EEPROM.get(EepromBrightness, brightness);
+  EEPROM.get(EepromHoldClickTime, hold);
+  EEPROM.get(EepromDClickTime, dclick);
+  EEPROM.get(EepromVoltsCalibrate, volt_calib);
+
+  Serial.printf("=================================================\n");
+  Serial.printf("dump_eeprom:\n");
+  Serial.printf("offset size  value\n");
+  Serial.printf("------ ----  -----\n");
+  Serial.printf("   %3d  (%d)  VfoFrequency=%ld\n", EepromFreq, sizeof(VfoFrequency), freq);
+  Serial.printf("   %3d  (%d)  EepromSelDigit=%d\n", EepromSelDigit, sizeof(SelOffset), offset);
+  Serial.printf("   %3d  (%d)  VfoClockOffset=%d\n", EepromVfoClockOffset, sizeof(VfoClockOffset), clkoffset);
+  Serial.printf("   %3d  (%d)  LcdContrast=%d\n", EepromContrast, sizeof(LcdContrast), contrast);
+  Serial.printf("   %3d  (%d)  LcdBrightness=%d\n", EepromBrightness, sizeof(LcdBrightness), brightness);
+  Serial.printf("   %3d  (%d)  ReHoldClickTime=%dmsec\n", EepromHoldClickTime, sizeof(ReHoldClickTime), hold);
+  Serial.printf("   %3d  (%d)  ReDClickTime=%dmsec\n", EepromDClickTime, sizeof(ReDClickTime), dclick);
+  Serial.printf("   %3d  (%d)  VoltsCalibrate=%d\n", EepromVoltsCalibrate, sizeof(VoltsCalibrate), volt_calib);
+
+  delay(DELAY_MS);
+
+  for (int i = 0; i < NumSaveSlots; ++i)
+  {
+    get_slot(i, freq, offset);
+    Serial.printf("Slot %d: freq=%ld, seldig=%d\n", i, freq, offset);
+    delay(DELAY_MS);
+  }
+
+  Serial.printf("=================================================\n");
+}
+
+//##############################################################################
+// Code to handle the DDS-60
+//
+// From: http://www.rocketnumbernine.com/2011/10/25/programming-the-ad9851-dds-synthesizer
+// Andrew Smallbone <andrew@rocketnumbernine.com>
+//
+// I've touched this a little bit, so any errors are mine!
+//##############################################################################
+
+//----------------------------------------
+// Pulse 'pin' high and then low very quickly.
+//----------------------------------------
+
+void dds_pulse_high(byte pin)
+{
+  digitalWrite(pin, HIGH);
+  digitalWrite(pin, LOW);
+}
+
+//----------------------------------------
+// Transfer a 'data' byte a bit at a time, LSB first, to DDS_DATA pin.
+//----------------------------------------
+
+void dds_tfr_byte(byte data)
+{
+  for (int i = 0; i < 8; ++i, data >>= 1)
+  {
+    digitalWrite(DDS_DATA, data & 0x01);
+    dds_pulse_high(DDS_W_CLK);
+  }
+}
+
+//----------------------------------------
+// Set the DDS-60 output frequency.
+//
+// Only set if VFO is online.
+//
+// Frequency of sinewave (datasheet page 12) will be
+// "<sys clock> * <frequency tuning word> / 2^32".
+// Rearranging: FTW = (frequency * 2^32) / sys_clock.
+// The 'VfoClockOffset' value is subtracted from <sys_clock> below.
+//----------------------------------------
+
+void dds_update(Frequency frequency)
+{
+  // if not online, do nothing
+  if (VfoMode != vfo_Online)
+    return;
+
+  // as in datasheet page 12 - modified to include calibration offset
+  ULONG data = (frequency * 4294967296) / (180000000 - VfoClockOffset);
+  //                        ^^^^^^^^^^ == 2**32
+
+#if (DEBUG & DEBUG_DDS)
+  Serial.printf("dds_update: ONLINE: frequency=%ld, VfoClockOffset=%d, data=%ld\n",
+                frequency, VfoClockOffset, data);
+#endif
+
+  // start programming the DDS-60
+  for (int b = 0; b < 4; ++b, data >>= 8)
+  {
+    dds_tfr_byte(data & 0xFF);
+  }
+  dds_tfr_byte(0x001);
+  dds_pulse_high(DDS_FQ_UD);
+}
+
+//----------------------------------------
+// Force the DDS into standby mode.
+// There is a standby bit in the control word, but setting frequency to zero works.
+//----------------------------------------
+
+void dds_standby(void)
+{
+#if (DEBUG & DEBUG_DDS)
+  Serial.printf("DDS into standby mode.\n");
+#endif
+
+  dds_update(0L);
+}
+
+//----------------------------------------
+// Force the DDS into online mode.
+//----------------------------------------
+
+void dds_online(void)
+{
+#if (DEBUG & DEBUG_FREQ)
+  Serial.printf("DDS into online mode, frequency=%dHz.\n", VfoFrequency);
+#endif
+
+  dds_update(VfoFrequency);
+}
+
+//----------------------------------------
+// Initialize the DDS hardware.
+// The VFO 'wakes up' in standby mode.
+//----------------------------------------
+
+void dds_setup(void)
+{
+  // all pins to outputs
+  pinMode(DDS_FQ_UD, OUTPUT);
+  pinMode(DDS_W_CLK, OUTPUT);
+  pinMode(DDS_DATA, OUTPUT);
+
+  // set serial load enable (Datasheet page 15 Fig. 17)
+  dds_pulse_high(DDS_W_CLK);
+  dds_pulse_high(DDS_FQ_UD);
+
+  // go into standby
+  dds_standby();
+}
+

 //----------------------------------------
 // Display the VFO mode on the screen..
@@ -883,7 +1136,7 @@
           return "ERROR";
         VfoFrequency = tmp_freq;
         display_sel_value(VfoFrequency, VfoSelectDigit, NumFreqChars,
-                          NumCols - NumFreqChars - 2, 0);
+                          LcdNumCols - NumFreqChars - 2 - 2, 0);
         return "OK";
       }
   }
@@ -1069,7 +1322,7 @@
   // write indexed item on lower row, right-justified
   lcd.setCursor(0, 1);
   lcd.print(BlankRow);
-  lcd.setCursor(NumCols - max_len, 1);
+  lcd.setCursor(LcdNumCols - max_len, 1);
   lcd.print(menu->items[item_num]->title);
 }

@@ -1366,21 +1619,20 @@

 //----------------------------------------
 // Display a value on the display with selected column underlined.
-//     value       the number to show
+//     value       the integer number to show
 //     sel_col     the selection offset of digit to underline
 //                 (0 is rightmost digit, increasing to the left)
 //     num_digits  the number of digits to show on the display
 //     col, row    position to display left-most digit at
 // If the value is too long it will be truncated at the left.
-//----------------------------------------
-
-// list of row 0 column positions for the display digits
-//int freq_digit_offset[] = {4, 5, 7, 8, 9, 11, 12, 13};
+// This routine inserts a comma every three columns.
+//----------------------------------------

 void display_sel_value(long value, int sel_col, int num_digits, int col, int row)
 {
   char buf [num_digits];
   int index = num_digits - sel_col - 1;
+  int comma_count = 3 - (num_digits % 3);  // columns to next comma

 #if (DEBUG & DEBUG_DISPLAY)
   Serial.printf("display_sel_value: value=%ld, sel_col=%d, num_digits=%d, col=%d, row=%d",
@@ -1397,7 +1649,7 @@
   // would prefer to set cursor position outside this function, but ไม่เป็นไร.
   lcd.setCursor(col, row);

-  // write each byte of buffer to display, handling leading spaces and selection
+  // write each byte of buffer to display, handling leading spaces, selection & commas
   bool lead_zero = true;
   for (int i = 0; i < num_digits; ++i)
   {
@@ -1428,8 +1680,21 @@
         lcd.write(char_val + '0');
       }
     }
-  }
-}
+    if (++comma_count >= 3)
+    {
+      if (i < num_digits - 1)
+      {
+        if (!lead_zero)
+          lcd.write(",");
+        else
+          lcd.write(" ");
+      }
+
+      comma_count = 0;
+    }
+  }
+}
+

 //----------------------------------------
 // Display an integer with sign on the display with selected column underlined.
@@ -1510,21 +1775,6 @@
 // Interrupt driven rotary encoder interface.  From code by Simon Merrett.
 // Based on insight from Oleg Mazurov, Nick Gammon, rt, Steve Spence.
 //##############################################################################
-
-// internal variables
-UINT ReHoldClickTime = DefaultHoldClickTime;
-UINT ReDClickTime = DefaultDClickTime;
-
-bool re_rotation = false;     // true if rotation occurred while knob down
-bool re_down = false;         // true while knob is down
-ULONG re_down_time = 0;       // milliseconds when knob is pressed down
-ULONG last_click = 0;         // time when last single click was found
-
-// expecting rising edge on pinA - at detent
-volatile byte aFlag = 0;
-
-// expecting rising edge on pinA - at detent
-volatile byte bFlag = 0;

 //----------------------------------------
 // Initialize the rotary encoder stuff.
@@ -1696,240 +1946,6 @@
 }

 //##############################################################################
-// Code to save/restore in EEPROM.
-//##############################################################################
-
-//----------------------------------------
-// Save VFO state to EEPROM.
-// Everything except slot data.
-//----------------------------------------
-
-void save_to_eeprom(void)
-{
-  EEPROM.put(EepromFreq, VfoFrequency);
-  EEPROM.put(EepromSelDigit, VfoSelectDigit);
-  EEPROM.put(EepromVfoClockOffset, VfoClockOffset);
-  EEPROM.put(EepromBrightness, LcdBrightness);
-  EEPROM.put(EepromContrast, LcdContrast);
-  EEPROM.put(EepromHoldClickTime, ReHoldClickTime);
-  EEPROM.put(EepromDClickTime, ReDClickTime);
-  EEPROM.put(EepromVoltsCalibrate, VoltsCalibrate);
-}
-
-//----------------------------------------
-// Restore VFO state from EEPROM.
-// Everything except slot data.
-//----------------------------------------
-
-void restore_from_eeprom(void)
-{
-  EEPROM.get(EepromFreq, VfoFrequency);
-  EEPROM.get(EepromSelDigit, VfoSelectDigit);
-  EEPROM.get(EepromVfoClockOffset, VfoClockOffset);
-  EEPROM.get(EepromBrightness, LcdBrightness);
-  EEPROM.get(EepromContrast, LcdContrast);
-  EEPROM.get(EepromHoldClickTime, ReHoldClickTime);
-  EEPROM.get(EepromDClickTime, ReDClickTime);
-  EEPROM.get(EepromVoltsCalibrate, VoltsCalibrate);
-}
-
-//----------------------------------------
-// Given slot number, return freq/offset.
-//     freq    pointer to Frequency item to be updated
-//     offset  pointer to selection offset item to be updated
-//----------------------------------------
-
-void get_slot(int slot_num, Frequency &freq, SelOffset &offset)
-{
-  int freq_address = EepromSaveFreqBase + slot_num * sizeof(Frequency);
-  int offset_address = EepromSaveOffsetBase + slot_num * sizeof(SelOffset);
-
-  EEPROM.get(freq_address, freq);
-  EEPROM.get(offset_address, offset);
-}
-
-//----------------------------------------
-// Put frequency/offset into given slot number.
-//     freq    pointer to Frequency item to be saved in slot
-//     offset  pointer to selection offset item to be saved in slot
-//----------------------------------------
-
-void put_slot(int slot_num, Frequency freq, SelOffset offset)
-{
-  int freq_address = EepromSaveFreqBase + slot_num * sizeof(Frequency);
-  int offset_address = EepromSaveOffsetBase + slot_num * sizeof(SelOffset);
-
-  EEPROM.put(freq_address, freq);
-  EEPROM.put(offset_address, offset);
-}
-
-//----------------------------------------
-// Print all EEPROM saved data to console.
-//----------------------------------------
-
-#define DELAY_MS 100  // not sure why we need a delay to print reliably
-
-void dump_eeprom(void)
-{
-  Frequency freq;
-  SelOffset offset;
-  int clkoffset;
-  int brightness;
-  int contrast;
-  UINT hold;
-  UINT dclick;
-  UINT volt_calib;
-
-  EEPROM.get(EepromFreq, freq);
-  EEPROM.get(EepromSelDigit, offset);
-  EEPROM.get(EepromVfoClockOffset, clkoffset);
-  EEPROM.get(EepromContrast, contrast);
-  EEPROM.get(EepromBrightness, brightness);
-  EEPROM.get(EepromHoldClickTime, hold);
-  EEPROM.get(EepromDClickTime, dclick);
-  EEPROM.get(EepromVoltsCalibrate, volt_calib);
-
-  Serial.printf("=================================================\n");
-  Serial.printf("dump_eeprom:\n");
-  Serial.printf("offset size  value\n");
-  Serial.printf("------ ----  -----\n");
-  Serial.printf("   %3d  (%d)  VfoFrequency=%ld\n", EepromFreq, sizeof(VfoFrequency), freq);
-  Serial.printf("   %3d  (%d)  EepromSelDigit=%d\n", EepromSelDigit, sizeof(SelOffset), offset);
-  Serial.printf("   %3d  (%d)  VfoClockOffset=%d\n", EepromVfoClockOffset, sizeof(VfoClockOffset), clkoffset);
-  Serial.printf("   %3d  (%d)  LcdContrast=%d\n", EepromContrast, sizeof(LcdContrast), contrast);
-  Serial.printf("   %3d  (%d)  LcdBrightness=%d\n", EepromBrightness, sizeof(LcdBrightness), brightness);
-  Serial.printf("   %3d  (%d)  ReHoldClickTime=%dmsec\n", EepromHoldClickTime, sizeof(ReHoldClickTime), hold);
-  Serial.printf("   %3d  (%d)  ReDClickTime=%dmsec\n", EepromDClickTime, sizeof(ReDClickTime), dclick);
-  Serial.printf("   %3d  (%d)  VoltsCalibrate=%d\n", EepromVoltsCalibrate, sizeof(VoltsCalibrate), volt_calib);
-
-  delay(DELAY_MS);
-
-  for (int i = 0; i < NumSaveSlots; ++i)
-  {
-    get_slot(i, freq, offset);
-    Serial.printf("Slot %d: freq=%ld, seldig=%d\n", i, freq, offset);
-    delay(DELAY_MS);
-  }
-
-  Serial.printf("=================================================\n");
-}
-
-//##############################################################################
-// Code to handle the DDS-60
-//
-// From: http://www.rocketnumbernine.com/2011/10/25/programming-the-ad9851-dds-synthesizer
-// Andrew Smallbone <andrew@rocketnumbernine.com>
-//
-// I've touched this a little bit, so any errors are mine!
-//##############################################################################
-
-//----------------------------------------
-// Pulse 'pin' high and then low very quickly.
-//----------------------------------------
-
-void dds_pulse_high(byte pin)
-{
-  digitalWrite(pin, HIGH);
-  digitalWrite(pin, LOW);
-}
-
-//----------------------------------------
-// Transfer a 'data' byte a bit at a time, LSB first, to DDS_DATA pin.
-//----------------------------------------
-
-void dds_tfr_byte(byte data)
-{
-  for (int i = 0; i < 8; ++i, data >>= 1)
-  {
-    digitalWrite(DDS_DATA, data & 0x01);
-    dds_pulse_high(DDS_W_CLK);
-  }
-}
-
-//----------------------------------------
-// Set the DDS-60 output frequency.
-//
-// Only set if VFO is online.
-//
-// Frequency of sinewave (datasheet page 12) will be
-// "<sys clock> * <frequency tuning word> / 2^32".
-// Rearranging: FTW = (frequency * 2^32) / sys_clock.
-// The 'VfoClockOffset' value is subtracted from <sys_clock> below.
-//----------------------------------------
-
-void dds_update(Frequency frequency)
-{
-  // if not online, do nothing
-  if (VfoMode != vfo_Online)
-    return;
-
-  // as in datasheet page 12 - modified to include calibration offset
-  ULONG data = (frequency * 4294967296) / (180000000 - VfoClockOffset);
-  //                        ^^^^^^^^^^ == 2**32
-
-#if (DEBUG & DEBUG_DDS)
-  Serial.printf("dds_update: ONLINE: frequency=%ld, VfoClockOffset=%d, data=%ld\n",
-                frequency, VfoClockOffset, data);
-#endif
-
-  // start programming the DDS-60
-  for (int b = 0; b < 4; ++b, data >>= 8)
-  {
-    dds_tfr_byte(data & 0xFF);
-  }
-  dds_tfr_byte(0x001);
-  dds_pulse_high(DDS_FQ_UD);
-}
-
-//----------------------------------------
-// Force the DDS into standby mode.
-// There is a standby bit in the control word, but setting frequency to zero works.
-//----------------------------------------
-
-void dds_standby(void)
-{
-#if (DEBUG & DEBUG_DDS)
-  Serial.printf("DDS into standby mode.\n");
-#endif
-
-  dds_update(0L);
-}
-
-//----------------------------------------
-// Force the DDS into online mode.
-//----------------------------------------
-
-void dds_online(void)
-{
-#if (DEBUG & DEBUG_FREQ)
-  Serial.printf("DDS into online mode, frequency=%dHz.\n", VfoFrequency);
-#endif
-
-  dds_update(VfoFrequency);
-}
-
-//----------------------------------------
-// Initialize the DDS hardware.
-// The VFO 'wakes up' in standby mode.
-//----------------------------------------
-
-void dds_setup(void)
-{
-  // all pins to outputs
-  pinMode(DDS_FQ_UD, OUTPUT);
-  pinMode(DDS_W_CLK, OUTPUT);
-  pinMode(DDS_DATA, OUTPUT);
-
-  // set serial load enable (Datasheet page 15 Fig. 17)
-  dds_pulse_high(DDS_W_CLK);
-  dds_pulse_high(DDS_FQ_UD);
-
-  // go into standby
-  dds_standby();
-}
-
-
-//##############################################################################
 // Main VFO code
 //##############################################################################

@@ -1941,7 +1957,7 @@
 void show_main_screen(void)
 {
   lcd.clear();
-  display_sel_value(VfoFrequency, VfoSelectDigit, NumFreqChars, NumCols - NumFreqChars - 2, 0);
+  display_sel_value(VfoFrequency, VfoSelectDigit, NumFreqChars, LcdNumCols - NumFreqChars - 2 - 2, 0);
   lcd.print("Hz");

   lcd.setCursor(0, 1);
@@ -1970,7 +1986,7 @@
   pinMode(mc_Contrast, OUTPUT);

   // initialize the display
-  lcd.begin(NumCols, NumRows);      // define display size
+  lcd.begin(LcdNumCols, LcdNumRows);      // define display size
   lcd.noCursor();

   // get state back from EEPROM, set display brightness/contrast
@@ -2063,10 +2079,10 @@
     lcd.setCursor(0, 1);
     lcd.write(byte(InUseChar));
   }
-  lcd.setCursor(4, 1);
+  lcd.setCursor(2, 1);
   lcd.write(slot_num + '0');
   lcd.print(":");
-  display_sel_value(freq, -1, NumFreqChars, NumCols - NumFreqChars - 2, 1);
+  display_sel_value(freq, -1, NumFreqChars, LcdNumCols - NumFreqChars - 2 - 2, 1);
   lcd.print("Hz");
 }

@@ -3023,7 +3039,7 @@
   measure_battery();

   // update the display
-  display_sel_value(VfoFrequency, VfoSelectDigit, NumFreqChars, NumCols - NumFreqChars - 2, 0);
+  display_sel_value(VfoFrequency, VfoSelectDigit, NumFreqChars, LcdNumCols - NumFreqChars - 2 - 2, 0);
   display_battery();

   // if online, update DDS-60 and write changes to EEPROM


print sensor debug output only on change

--- GeheimTuer.ino
+++ GeheimTuer.ino
@@ -246,24 +246,24 @@
 const unsigned long ledMoveMin = 50; // minimum move interval if drivePWM == 255
 const unsigned long ledMoveMax = 305; // maximum move interval if drivePWM == 0

+const int dsMax = 3; // register at most dsMax DS18B20 sensors
+byte dsAddrs[dsMax][8]; // 1-wire addresses
+byte dsCount; // registered sensors
+signed int dsResults[dsMax];
+
 unsigned long dsMillis = 0;
 const unsigned long dsInterval = 1000; // sensor read interval
-const signed int tempMin = 35/0.0625; // run fan at minimum speed at tempMin
-const signed int tempMax = 45/0.0625; // run fan at full speed above tempMax
-const signed int tempHyst = 5/0.0625; // shut off fan at tempMin-tempHyst
+const signed int tempMin = 33/0.0625; // run fan at minimum speed at tempMin
+const signed int tempMax = 40/0.0625; // run fan at full speed above tempMax
+const signed int tempHyst = 3/0.0625; // shut off fan at tempMin-tempHyst

 byte fanPWM;
 const byte fanMin = 170; // minimum PWM limit at temp > tempMin
 const byte fanMax = 255; // maximum PWM limit at temp < tempMax

-
 bool swFront, swBack, swTrigger, motorDiagA, motorDiagB, pirTrigger; // debounced inputs, can be reset to wait for next cycle
 bool swFrontDeglitch, swBackDeglitch, swTriggerDeglitch, motorDiagADeglitch, motorDiagBDeglitch, pirDeglitch; // debounced inputs, reset by every detected edge
 uint16_t swFrontDebounce, swBackDebounce, swTriggerDebounce, motorDiagADebounce, motorDiagBDebounce, pirDebounce; // debounce shift registers
-
-const int dsMax = 3; // register at most dsMax sensors
-byte dsAddrs[dsMax][8]; // 1-wire addresses
-byte dsCount; // registered sensors

 void setup() {
@@ -308,37 +308,8 @@

   pinMode(pirPin, INPUT);

-  // scan 1-wire bus for temperature sensors
-  byte addr[8];
-  byte dsIdx = 0;
-
-  ds.reset_search();
-  Serial.print(F("Searching 1-wire...\r\n"));
-
-  while (ds.search(addr) && dsIdx < dsMax) {
-    Serial.print(F("Detected device: "));
-    for (int i = 0; i < 8; i++) {
-      Serial.print(addr[i], HEX);
-    }
-
-    Serial.print(F(" - "));
-    if (OneWire::crc8(addr, 7) != addr[7]) {
-      Serial.print(F("invalid CRC!\r\n"));
-      continue;
-    }
-
-    if (addr[0] == 0x28) {
-      for (int i = 0; i < 8; i++) {
-        dsAddrs[dsIdx][i] = addr[i];
-      }
-      dsIdx++;
-      Serial.print(F("DS18B20 registered\r\n"));
-    } else {
-      Serial.print(F("unknown device ignored\r\n"));
-     }
-  }
-  dsCount = dsIdx;
-  ds.reset_search();
+  // register sensors
+  scan1Wire();

   // initialize debounce registers, assume steady state
   swFrontDebounce = (swFront = swFrontDeglitch = digitalRead(switchFront)) * 0xFFFF;
@@ -403,11 +374,6 @@
   }
   lastMillis = currentMillis;
   // assume that none of the following intervals overflow
-
-  /*
-    debug(currentMillis, F("Elapsed millis: "));
-    Serial.println(elapsedMillis);
-  */

   // fast debounce driver error signals to filter short glitches
@@ -476,6 +442,9 @@
       case 'K':
         setLeds1(black, ledSolid);
         break;
+      case '1':
+        scan1Wire();
+        break;
     }
   }

@@ -550,7 +519,7 @@
         doorState = doorOpen;
         break;
       }
-    // fall-through to next case
+      // fall-through to next case

     case doorClosing:
       if (doorState == doorClosing && swFront == LOW) {
@@ -783,20 +752,16 @@

   if (dsMillis >= dsInterval) {
     dsMillis = 0;
-    signed int maxTemp = 0;

     byte data[9];
     byte dsRead = 0;
+    signed int maxTemp = 0;

     for (int i = 0; i < dsCount; i++) {
       // read temperature
       ds.reset();
       ds.select(dsAddrs[i]);
       ds.write(0xBE);
-      debug(currentMillis, F("Sensor "));
-      Serial.print(i);
-      Serial.print(F(": "));
-
       for (int j = 0; j < 9; j++) {
         data[j] = ds.read();
       }
@@ -806,13 +771,24 @@
         if (temp > maxTemp) {
           maxTemp = temp;
         }
-        Serial.print(temp);
-        Serial.print(F(" - "));
-        Serial.print((double)temp*0.0625, 2);
-        Serial.print(F("°C\r\n"));
+
+        if (temp != dsResults[i]) {
+          dsResults[i] = temp;
+
+          debug(currentMillis, F("Sensor "));
+          Serial.print(i);
+          Serial.print(F(": "));
+          Serial.print(temp);
+          Serial.print(F(" - "));
+          Serial.print((double)temp*0.0625, 2);
+          Serial.print(F("°C\r\n"));
+        }
+
         dsRead++;
       } else {
-        Serial.print(F("invalid CRC!\r\n"));
+        debug(currentMillis, F("Sensor "));
+        Serial.print(i);
+        Serial.print(F(": invalid CRC!\r\n"));
       }

       // start next conversion
@@ -833,9 +809,12 @@
           fanPWM = 255;
         }
       } else if (maxTemp >= tempMin) {
-        fanPWM = map(maxTemp, tempMin, tempMax, fanMin, fanMax);
-        Serial.print(F("Fan PWM: "));
-        Serial.println(fanPWM);
+        byte newPWM = map(maxTemp, tempMin, tempMax, fanMin, fanMax);
+        if (newPWM != fanPWM) {
+          fanPWM = newPWM;
+          debug(currentMillis, F("Fan PWM: "));
+          Serial.println(fanPWM);
+        }
       } else if (fanPWM > 0) {
         fanPWM = fanMin;
       }
@@ -855,6 +834,40 @@
   Serial.print(timestamp);
   Serial.write(' ');
   Serial.print(string);
+}
+
+// scan 1-wire bus for temperature sensors
+void scan1Wire() {
+  byte addr[8];
+  byte dsIdx = 0;
+
+  ds.reset_search();
+  Serial.print(F("Searching 1-wire...\r\n"));
+
+  while (ds.search(addr) && dsIdx < dsMax) {
+    Serial.print(F("Detected device: "));
+    for (int i = 0; i < 8; i++) {
+      Serial.print(addr[i], HEX);
+    }
+
+    Serial.print(F(" - "));
+    if (OneWire::crc8(addr, 7) != addr[7]) {
+      Serial.print(F("invalid CRC!\r\n"));
+      continue;
+    }
+
+    if (addr[0] == 0x28) {
+      for (int i = 0; i < 8; i++) {
+        dsAddrs[dsIdx][i] = addr[i];
+      }
+      dsIdx++;
+      Serial.print(F("DS18B20 registered\r\n"));
+    } else {
+      Serial.print(F("unknown device ignored\r\n"));
+     }
+  }
+  dsCount = dsIdx;
+  ds.reset_search();
 }

 //__attribute__((always_inline))


[feat] correctly implement digitalWrite

[feat] correctly implement digitalWrite

--- src/du.ino
+++ src/du.ino
@@ -54,7 +54,9 @@
  * Digital write
  */
 void dw(char *pin, char *val) {
-  Serial.println('1');
+  int p = atoi(pin);
+  if (strcmp(val, "00") == 0) digitalWrite(p, LOW);
+  else digitalWrite(p, HIGH);
 }

 /*