refactored again

refactored again

--- src/firmware/Zeppelin/Zeppelin.ino
+++ src/firmware/Zeppelin/Zeppelin.ino
@@ -1,41 +1,51 @@
+//general definitions to interface with the hardware

+
+#define UP_MOTOR_FORWARD 5
+#define UP_MOTOR_BACKWARD 6
+#define UP_MOTOR_ENABLE 10
+
+#define RIGHT_MOTOR_FORWARD 7
+#define RIGHT_MOTOR_BACKWARD 8
+#define RIGHT_MOTOR_ENABLE 3
+
+#define LEFT_MOTOR_FORWARD 13
+#define LEFT_MOTOR_BACKWARD 12
+#define LEFT_MOTOR_ENABLE 11
+
+//general definitions as parameters of the
 #define MOTOR_MAX_PWM 255.0

-const int motor_right_forward = 7;
-const int motor_right_backward = 8;
-const int motor_right_enable = 3;
-
-const int motor_left_forward = 13;
-const int motor_left_backward = 12;
-const int motor_left_enable = 11;
-
-const int motor_up_forward = 5;//TODO set the adequate value
-const int motor_up_backward = 6;//TODO set the adequate value
-const int motor_up_enable = 10;//TODO set the adequate value

-byte motor_right_pwm = 0;
-byte motor_left_pwm = 0;
-byte motor_up_pwm = 0;

-float motor_right_speed = 0;
-float motor_left_speed = 0;
-float motor_up_speed = 0;
+byte right_motor_pwm = 0;
+byte left_motor_pwm = 0;
+
+float right_motor_velocity = 0;
+float left_motor_velocity = 0;

 char incomingByte_X = 0;
 char incomingByte_Y = 0;
-char incomingByte_Z = 0;

 const float X_factor = 1.0;
 const float Y_factor = 1.0;
-const float Z_factor = 1.0;

 float min_right;
 float max_right;
 float min_left;
 float max_left;
+
+
+#ifndef TEST_XY_ONLY
+byte up_motor_pwm = 0;
+float up_motor_velocity = 0;
+char incomingByte_Z = 0;
+const float Z_factor = 1.0;
 float min_up;
 float max_up;
+#endif
+

 const long interval = 200;
 long previousMillis = 0;
@@ -47,40 +57,45 @@

 //computing Motor velocity VS an X,Y control vector
-float compute_Right_Motor_Raw_Speed(float value_x, float value_y){
+float compute_Right_Motor_Raw_Velocity(float value_x, float value_y){
   return (X_factor*value_x - Y_factor*value_y*sign(value_x));
 }

-float compute_Left_Motor_Raw_Speed(float value_x, float value_y){
+float compute_Left_Motor_Raw_Velocity(float value_x, float value_y){
   return (X_factor*value_x + Y_factor*value_y*sign(value_x));
 }

-float compute_Up_Motor_Raw_Speed(float value_z){
+#ifndef TEST_XY_ONLY
+float compute_Up_Motor_Raw_Velocity(float value_z){
   return (Z_factor*value_z);
 }
+#endif

 //computing Motor velocity VS an X,Y control vector
-float compute_Right_Motor_Speed(float value_x, float value_y){
-    return map(compute_Right_Motor_Raw_Speed(value_x, value_y), min_right, max_right,-MOTOR_MAX_PWM,MOTOR_MAX_PWM);
+float compute_Right_Motor_Velocity(float value_x, float value_y){
+    return map(compute_Right_Motor_Raw_Velocity(value_x, value_y), min_right, max_right,-MOTOR_MAX_PWM,MOTOR_MAX_PWM);
 }

-float compute_Left_Motor_Speed(float value_x, float value_y){
-  return map(compute_Left_Motor_Raw_Speed(value_x, value_y), min_left, max_left,-MOTOR_MAX_PWM,MOTOR_MAX_PWM);
+float compute_Left_Motor_Velocity(float value_x, float value_y){
+  return map(compute_Left_Motor_Raw_Velocity(value_x, value_y), min_left, max_left,-MOTOR_MAX_PWM,MOTOR_MAX_PWM);
 }

-float compute_Up_Motor_Speed(float value_z){
-  return map(compute_Up_Motor_Raw_Speed(value_z), min_up, max_up,-MOTOR_MAX_PWM,MOTOR_MAX_PWM);
+#ifndef TEST_XY_ONLY
+float compute_Up_Motor_Velocity(float value_z){
+  return map(compute_Up_Motor_Raw_Velocity(value_z), min_up, max_up,-MOTOR_MAX_PWM,MOTOR_MAX_PWM);
 }
+#endif

-
-//this function is used to enable the use of compute_XXX_Motor_Speed
+//this function is used to enable the use of compute_XXX_Motor_Velocity
 void compute_Resize_Parameters(){
-   min_right = compute_Right_Motor_Raw_Speed(-100.0, -100.0);
-   max_right = compute_Right_Motor_Raw_Speed(100.0, -100.0);
-   min_left = compute_Left_Motor_Raw_Speed(-100.0, 100.0);
-   max_left = compute_Left_Motor_Raw_Speed(100.0, 100.0);
-   min_up = compute_Up_Motor_Raw_Speed(-100.0);
-   max_up = compute_Up_Motor_Raw_Speed(100.0);
+   min_right = compute_Right_Motor_Raw_Velocity(-100.0, -100.0);
+   max_right = compute_Right_Motor_Raw_Velocity(100.0, -100.0);
+   min_left = compute_Left_Motor_Raw_Velocity(-100.0, 100.0);
+   max_left = compute_Left_Motor_Raw_Velocity(100.0, 100.0);
+#ifndef TEST_XY_ONLY
+   min_up = compute_Up_Motor_Raw_Velocity(-100.0);
+   max_up = compute_Up_Motor_Raw_Velocity(100.0);
+#endif
 }

@@ -88,27 +103,30 @@
  //initialize Serial communication
  Serial.begin(9600);
  Serial.flush();
- //initializing pins used to control motors
- pinMode(motor_right_forward, OUTPUT);
- pinMode(motor_right_backward, OUTPUT);
- pinMode(motor_left_forward, OUTPUT);
- pinMode(motor_left_backward, OUTPUT);
- pinMode(motor_up_forward, OUTPUT);
- pinMode(motor_up_backward, OUTPUT);
+ //initializing pins used to control motors power
+ pinMode(RIGHT_MOTOR_FORWARD, OUTPUT);
+ pinMode(RIGHT_MOTOR_BACKWARD, OUTPUT);
+ pinMode(LEFT_MOTOR_FORWARD, OUTPUT);
+ pinMode(LEFT_MOTOR_BACKWARD, OUTPUT);
+//initializing pins used to control motors rotation clockwise or trigonometricwise
+ digitalWrite(RIGHT_MOTOR_ENABLE, LOW);
+ digitalWrite(LEFT_MOTOR_ENABLE, LOW);
+
+#ifndef TEST_XY_ONLY
+ pinMode(UP_MOTOR_FORWARD, OUTPUT);
+ pinMode(UP_MOTOR_BACKWARD, OUTPUT);
+ digitalWrite(UP_MOTOR_ENABLE, LOW);
+#endif

-
- digitalWrite(motor_right_enable, LOW);
- digitalWrite(motor_left_enable, LOW);
- digitalWrite(motor_up_enable, LOW);
  compute_Resize_Parameters();
 }

 void loop() {

-    //continuously controlling motors
-    analogWrite(motor_right_enable, motor_right_pwm);
-    analogWrite(motor_left_enable, motor_left_pwm);
-    analogWrite(motor_up_enable, motor_up_pwm);
+    //continuously controlling motors by applying the computed pwm
+    analogWrite(RIGHT_MOTOR_ENABLE, right_motor_pwm);
+    analogWrite(LEFT_MOTOR_ENABLE, left_motor_pwm);
+    analogWrite(UP_MOTOR_ENABLE, up_motor_pwm);
     delay(100);//control loop = 10Hz
 }

@@ -120,44 +138,52 @@
     incomingByte_X= constrain(incomingByte_X, -100,100);
     incomingByte_Y = Serial.read();
     incomingByte_Y= constrain(incomingByte_Y, -100,100);
+#ifndef TEST_XY_ONLY
     incomingByte_Z = Serial.read();
     incomingByte_Z= constrain(incomingByte_Z, -100,100);
-
-    //computing new speed for wheels
+#endif
+    //computing new desired velocity for each motor
+    right_motor_velocity = compute_Right_Motor_Velocity(float(incomingByte_X), float(incomingByte_Y));
+    left_motor_velocity = compute_Left_Motor_Velocity(float(incomingByte_X), float(incomingByte_Y));
+#ifndef TEST_XY_ONLY
+    up_motor_velocity = compute_Up_Motor_Velocity(float(incomingByte_Z));
+#endif
     //configuring right motor PWM
-    motor_right_pwm = byte(abs(motor_right_speed));
-    if(motor_right_speed >= 0){
-        digitalWrite(motor_right_forward, HIGH);
-        digitalWrite(motor_right_backward, LOW);
+    right_motor_pwm = byte(abs(right_motor_velocity));
+    if(right_motor_velocity >= 0){
+        digitalWrite(RIGHT_MOTOR_FORWARD, HIGH);
+        digitalWrite(RIGHT_MOTOR_BACKWARD, LOW);
     }
     else{
-        digitalWrite(motor_right_forward, LOW);
-        digitalWrite(motor_right_backward, HIGH);
+        digitalWrite(RIGHT_MOTOR_FORWARD, LOW);
+        digitalWrite(RIGHT_MOTOR_BACKWARD, HIGH);
     }
     //configuring left motor PWM
-    motor_left_pwm = byte(abs(motor_left_speed));
-    if(motor_left_speed >= 0){
-        digitalWrite(motor_left_forward, HIGH);
-        digitalWrite(motor_left_backward, LOW);
+    left_motor_pwm = byte(abs(left_motor_velocity));
+    if(left_motor_velocity >= 0){
+        digitalWrite(LEFT_MOTOR_FORWARD, HIGH);
+        digitalWrite(LEFT_MOTOR_BACKWARD, LOW);
     }
     else{
-        digitalWrite(motor_left_forward, LOW);
-        digitalWrite(motor_left_backward, HIGH);
+        digitalWrite(LEFT_MOTOR_FORWARD, LOW);
+        digitalWrite(LEFT_MOTOR_BACKWARD, HIGH);
     }
-    //configuring up motor PWM
-    motor_up_pwm = byte(abs(motor_up_speed));
-    if(motor_up_speed >= 0){
-        digitalWrite(motor_up_forward, HIGH);
-        digitalWrite(motor_up_backward, LOW);
+#ifndef TEST_XY_ONLY
+   //configuring up motor PWM
+    up_motor_pwm = byte(abs(up_motor_velocity));
+    if(up_motor_velocity >= 0){
+        digitalWrite(UP_MOTOR_FORWARD, HIGH);
+        digitalWrite(UP_MOTOR_BACKWARD, LOW);
     }
     else{
-        digitalWrite(motor_up_forward, LOW);
-        digitalWrite(motor_up_backward, HIGH);
+        digitalWrite(UP_MOTOR_FORWARD, LOW);
+        digitalWrite(UP_MOTOR_BACKWARD, HIGH);
     }
+#endif
     //some debugging info
-    //Serial.write(motor_right_pwm);
-    //Serial.write(motor_left_pwm);
-    //Serial.write(motor_up_pwm);
+    //Serial.write(right_motor_pwm);
+    //Serial.write(left_motor_pwm);
+    //Serial.write(up_motor_pwm);
     Serial.flush();
   }
 }


Decrease touch sensitivity

Decrease touch sensitivity

--- PushStart.ino
+++ PushStart.ino
@@ -121,7 +121,7 @@

 void loop() {

-  uint16_t value = analogTouchRead(pinCap);
+  uint16_t value = analogTouchRead(pinCap, 100);

   // Self calibrate capacitive touch
   static uint16_t ref = 0xFFFF;
@@ -130,7 +130,7 @@
   else if (value > (ref >> offset))
     ref++;

-  bool touched = (value - (ref >> offset)) > 40;
+  bool touched = (value - (ref >> offset)) > 100;

   if (touched & !pressed) {
     touchStart = millis();


speed control

speed control

--- oledPong/oledPong.ino
+++ oledPong/oledPong.ino
@@ -49,13 +49,14 @@
 #define PADDLE_XR 126

 #define SPD0 0
-#define SPD1 48 //Ball speed - the smaller this number is, the faster the ball goes
+int16_t spd = 48;
+
+bool potSpeedControl = true; //false = speed is set by "int16_t spd = [value]" above, true = speed is set by the potentiometer on SPEEDPOT_PIN (default A15, CHANGE THIS IF YOU ARE USING ARDUINO UNO)

 #define JOYPIN_L 2 //Analog pin of the left joystick
 #define JOYPIN_R 0 //Analog pin of the right joystick
-
-int16_t joyYL;
-int16_t joyYR;
+#define SPEEDPOT_PIN 15//Analog pin of the speed potentiometer
+
 int16_t paddleL;
 int16_t paddleR;
 uint8_t movementVal;
@@ -93,17 +94,17 @@
     lastballY = 32;
   }
   if (i == UP_RIGHT) {
-    ballX = lastballX + map(movementVal, SPD0, SPD1, 0, 128);
-    ballY = lastballY - map(movementVal, SPD0, SPD1, 0, num);
+    ballX = lastballX + map(movementVal, SPD0, spd, 0, 128);
+    ballY = lastballY - map(movementVal, SPD0, spd, 0, num);
   } else if (i == UP_LEFT) {
-    ballX = lastballX - map(movementVal, SPD0, SPD1, 0, 128);
-    ballY = lastballY - map(movementVal, SPD0, SPD1, 0, num);
+    ballX = lastballX - map(movementVal, SPD0, spd, 0, 128);
+    ballY = lastballY - map(movementVal, SPD0, spd, 0, num);
   } else if (i == DOWN_RIGHT) {
-    ballX = lastballX + map(movementVal, SPD0, SPD1, 0, 128);
-    ballY = lastballY + map(movementVal, SPD0, SPD1, 0, num);
+    ballX = lastballX + map(movementVal, SPD0, spd, 0, 128);
+    ballY = lastballY + map(movementVal, SPD0, spd, 0, num);
   } else if (i == DOWN_LEFT) {
-    ballX = lastballX - map(movementVal, SPD0, SPD1, 0, 128);
-    ballY = lastballY + map(movementVal, SPD0, SPD1, 0, num);
+    ballX = lastballX - map(movementVal, SPD0, spd, 0, 128);
+    ballY = lastballY + map(movementVal, SPD0, spd, 0, num);
   }
 }

@@ -170,6 +171,7 @@
 void loop() {
   int16_t joyL = analogRead(JOYPIN_L);
   int16_t joyR = analogRead(JOYPIN_R);
+  if (potSpeedControl == true){spd = map(analogRead(SPEEDPOT_PIN), 0, 1023, 28, 64);}
   paddleL = map(joyL, 0, 1023, 0, 59);
   paddleR = map(joyR, 0, 1023, 0, 59);


Update old_pos.

Update old_pos.

--- brotherKH930_arduino.ino
+++ brotherKH930_arduino.ino
@@ -15,6 +15,7 @@
   int pos = brother.position();

   if (old_pos != pos) {
+    old_pos = pos;
     Serial.print("@");
     Serial.print(pos);
     Serial.print("  ");


removes some whitespace from fona button example


tweak fona button example gprs enable

tweak fona button example gprs enable


Line-in

Line-in

--- examples/sorenson/sorenson.ino
+++ examples/sorenson/sorenson.ino
@@ -85,8 +85,10 @@

   AudioMemory(30);
   audioShield.enable();
-  audioShield.inputSelect(AUDIO_INPUT_MIC);
-  audioShield.micGain(100);
+  audioShield.inputSelect(AUDIO_INPUT_LINEIN);
+  audioShield.lineInLevel(15);
+  //audioShield.inputSelect(AUDIO_INPUT_MIC);
+  //audioShield.micGain(100);
   note.begin(.90);

   input = new AudioShieldInput(&peak, &note);


Replaced core functions strcat with SDK version

--- src/main.ino
+++ src/main.ino
@@ -24,7 +24,7 @@

   char cidBuf[7];
   sprintf(cidBuf, "%06X", ESP.getChipId());
-  strcat(identifier, cidBuf);
+  os_strcat(identifier, cidBuf);

   return identifier;
 }


(^) arduino (CEU_RET)

(^) arduino (CEU_RET)

--- arduino/poll.ino
+++ arduino/poll.ino
@@ -258,17 +258,15 @@
     }
 #endif

+#ifdef POLLING_INTERVAL
+    if (POLLING_INTERVAL > dt)
+        delayMicroseconds(POLLING_INTERVAL-dt);
+#endif
+
     u32 now = micros();
     s32 dt = now - old;     // no problems with overflow
     old = now;
-
-#ifdef POLLING_INTERVAL
-    if (POLLING_INTERVAL > dt)
-        delayMicroseconds(POLLING_INTERVAL-dt);
-#endif
-    int s = ceu_go_wclock(NULL, dt);
-    while (s == CEU_RET_WCLOCK)
-        s = ceu_go_wclock(NULL, 0);
+    ceu_go_wclock(NULL, dt);

 #ifdef CEU_ASYNCS
     ceu_go_async(NULL, NULL);


Wrap from first file to last when rewinding

--- Arduino/LightPlayer/LightPlayer.ino
+++ Arduino/LightPlayer/LightPlayer.ino
@@ -421,36 +421,40 @@
   }
 }

-bool previousFile() {
+void previousFile()
+{
   if (infile.isOpen()) {
     infile.close();
   }

-  // dir size is 32.
-  uint16_t index = sd.vwd()->curPosition()/32;
-  if (index < 2) return false;
-  // position to possible previous file location.
-  index -= 2;
-
-  do {
-    infile.open(sd.vwd(), index, O_READ);
-
-    if (infile.isOpen()) {
-      if (!infile.isHidden() && !infile.isSystem()) {
+  while (true) {
+    // dir size is 32.
+    uint16_t index = sd.vwd()->curPosition()/32;
+    if (index < 2) {
+      // Advance to past last file of directory.
+      dir_t dir;
+      while (sd.vwd()->readDir(&dir) > 0);
+      continue;
+    }
+    // position to possible previous file location.
+    index -= 2;
+
+    do {
+      infile.open(sd.vwd(), index, O_READ);
+
+      if (infile.isOpen()) {
+        if (!infile.isHidden() && !infile.isSystem()) {
 #ifdef DEBUG
-        char buf[13];
-        infile.getName(buf, sizeof(buf));
-        cout << F("\nOpened prev file: ") << buf;
+          char buf[13];
+          infile.getName(buf, sizeof(buf));
+          cout << F("\nOpened prev file: ") << buf;
 #endif
-        return true;
-      }
-      infile.close();
-    } else {
-      return false;
-    }
-  } while (index-- > 0);
-
-  return false;
+          return;
+        }
+        infile.close();
+      }
+    } while (index-- > 0);
+  }
 }

 bool readFrame()
@@ -458,11 +462,7 @@
   int32_t seek_offset = (int32_t)speed * sizeof(frame);
   if (speed < 0 && infile.curPosition() < -seek_offset) {
     // Going backwards, and reached the start of this file.
-    if (!previousFile()) {
-      // No more files.  Restart from the first at normal speed.
-      speed = 0;
-      return false;
-    }
+    previousFile();
     // Successfully opened previous file - start from the end.
     infile.seekEnd();
   }


Modify int data types for cross platforms

--- examples/AccessControl/AccessControl.ino
+++ examples/AccessControl/AccessControl.ino
@@ -62,19 +62,19 @@

 #include <EEPROM.h>     // We are going to read and write PICC's UIDs from/to EEPROM
 #include <SPI.h>        // RC522 Module uses SPI protocol
-#include <MFRC522.h>	// Library for Mifare RC522 Devices
+#include <MFRC522.h>  // Library for Mifare RC522 Devices

 /*
-	Instead of a Relay you may want to use a servo. Servos can lock and unlock door locks too
-	Relay will be used by default
+  Instead of a Relay you may want to use a servo. Servos can lock and unlock door locks too
+  Relay will be used by default
 */

 // #include <Servo.h>

 /*
-	For visualizing whats going on hardware	we need some leds and to control door lock a relay and a wipe button
-	(or some other hardware) Used common anode led,digitalWriting HIGH turns OFF led Mind that if you are going
-	to use common cathode led or just seperate leds, simply comment out #define COMMON_ANODE,
+  For visualizing whats going on hardware we need some leds and to control door lock a relay and a wipe button
+  (or some other hardware) Used common anode led,digitalWriting HIGH turns OFF led Mind that if you are going
+  to use common cathode led or just seperate leds, simply comment out #define COMMON_ANODE,
 */

 #define COMMON_ANODE
@@ -87,27 +87,27 @@
 #define LED_OFF LOW
 #endif

-#define redLed 7		// Set Led Pins
+#define redLed 7    // Set Led Pins
 #define greenLed 6
 #define blueLed 5

-#define relay 4			// Set Relay Pin
-#define wipeB 3			// Button pin for WipeMode
+#define relay 4     // Set Relay Pin
+#define wipeB 3     // Button pin for WipeMode

 boolean match = false;          // initialize card match to false
-boolean programMode = false;	// initialize programming mode to false
+boolean programMode = false;  // initialize programming mode to false
 boolean replaceMaster = false;

-int successRead;		// Variable integer to keep if we have Successful Read from Reader
-
-byte storedCard[4];		// Stores an ID read from EEPROM
-byte readCard[4];		// Stores scanned ID read from RFID Module
-byte masterCard[4];		// Stores master card's ID read from EEPROM
+uint8_t successRead;    // Variable integer to keep if we have Successful Read from Reader
+
+byte storedCard[4];   // Stores an ID read from EEPROM
+byte readCard[4];   // Stores scanned ID read from RFID Module
+byte masterCard[4];   // Stores master card's ID read from EEPROM

 // Create MFRC522 instance.
 #define SS_PIN 10
 #define RST_PIN 9
-MFRC522 mfrc522(SS_PIN, RST_PIN);
+MFRC522 mfrc522(SS_PIN, RST_PIN);

 ///////////////////////////////////////// Setup ///////////////////////////////////
 void setup() {
@@ -115,16 +115,16 @@
   pinMode(redLed, OUTPUT);
   pinMode(greenLed, OUTPUT);
   pinMode(blueLed, OUTPUT);
-  pinMode(wipeB, INPUT_PULLUP);		// Enable pin's pull up resistor
+  pinMode(wipeB, INPUT_PULLUP);   // Enable pin's pull up resistor
   pinMode(relay, OUTPUT);
   //Be careful how relay circuit behave on while resetting or power-cycling your Arduino
-  digitalWrite(relay, HIGH);		// Make sure door is locked
-  digitalWrite(redLed, LED_OFF);	// Make sure led is off
-  digitalWrite(greenLed, LED_OFF);	// Make sure led is off
-  digitalWrite(blueLed, LED_OFF);	// Make sure led is off
+  digitalWrite(relay, HIGH);    // Make sure door is locked
+  digitalWrite(redLed, LED_OFF);  // Make sure led is off
+  digitalWrite(greenLed, LED_OFF);  // Make sure led is off
+  digitalWrite(blueLed, LED_OFF); // Make sure led is off

   //Protocol Configuration
-  Serial.begin(9600);	 // Initialize serial communications with PC
+  Serial.begin(9600);  // Initialize serial communications with PC
   SPI.begin();           // MFRC522 Hardware uses SPI protocol
   mfrc522.PCD_Init();    // Initialize MFRC522 Hardware

@@ -132,27 +132,27 @@
   //mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);

   Serial.println(F("Access Control Example v0.1"));   // For debugging purposes
-  ShowReaderDetails();	// Show details of PCD - MFRC522 Card Reader details
+  ShowReaderDetails();  // Show details of PCD - MFRC522 Card Reader details

   //Wipe Code - If the Button (wipeB) Pressed while setup run (powered on) it wipes EEPROM
-  if (digitalRead(wipeB) == LOW) {	// when button pressed pin should get low, button connected to ground
-    digitalWrite(redLed, LED_ON);	// Red Led stays on to inform user we are going to wipe
+  if (digitalRead(wipeB) == LOW) {  // when button pressed pin should get low, button connected to ground
+    digitalWrite(redLed, LED_ON); // Red Led stays on to inform user we are going to wipe
     Serial.println(F("Wipe Button Pressed"));
     Serial.println(F("You have 15 seconds to Cancel"));
     Serial.println(F("This will be remove all records and cannot be undone"));
     delay(15000);                        // Give user enough time to cancel operation
     if (digitalRead(wipeB) == LOW) {    // If button still be pressed, wipe EEPROM
       Serial.println(F("Starting Wiping EEPROM"));
-      for (int x = 0; x < EEPROM.length(); x = x + 1) {    //Loop end of EEPROM address
+      for (uint8_t x = 0; x < EEPROM.length(); x = x + 1) {    //Loop end of EEPROM address
         if (EEPROM.read(x) == 0) {              //If EEPROM address 0
           // do nothing, already clear, go to the next address in order to save time and reduce writes to EEPROM
         }
         else {
-          EEPROM.write(x, 0); 			// if not write 0 to clear, it takes 3.3mS
+          EEPROM.write(x, 0);       // if not write 0 to clear, it takes 3.3mS
         }
       }
       Serial.println(F("EEPROM Successfully Wiped"));
-      digitalWrite(redLed, LED_OFF); 	// visualize a successful wipe
+      digitalWrite(redLed, LED_OFF);  // visualize a successful wipe
       delay(200);
       digitalWrite(redLed, LED_ON);
       delay(200);
@@ -182,7 +182,7 @@
       delay(200);
     }
     while (!successRead);                  // Program will not go further while you not get a successful read
-    for ( int j = 0; j < 4; j++ ) {        // Loop 4 times
+    for ( uint8_t j = 0; j < 4; j++ ) {        // Loop 4 times
       EEPROM.write( 2 + j, readCard[j] );  // Write scanned PICC's UID to EEPROM, start from address 3
     }
     EEPROM.write(1, 143);                  // Write to EEPROM we defined Master Card.
@@ -190,7 +190,7 @@
   }
   Serial.println(F("-------------------"));
   Serial.println(F("Master Card's UID"));
-  for ( int i = 0; i < 4; i++ ) {          // Read Master Card's UID from EEPROM
+  for ( uint8_t i = 0; i < 4; i++ ) {          // Read Master Card's UID from EEPROM
     masterCard[i] = EEPROM.read(2 + i);    // Write it to masterCard
     Serial.print(masterCard[i], HEX);
   }
@@ -205,7 +205,7 @@
 ///////////////////////////////////////// Main Loop ///////////////////////////////////
 void loop () {
   do {
-    successRead = getID(); 	// sets successRead to 1 when we get read from reader otherwise 0
+    successRead = getID();  // sets successRead to 1 when we get read from reader otherwise 0
     // When device is in use if wipe button pressed for 10 seconds initialize Master Card wiping
     if (digitalRead(wipeB) == LOW) { // Check if button is pressed
       // Visualize normal operation is iterrupted by pressing wipe button Red is like more Warning to user
@@ -226,10 +226,10 @@
       cycleLeds();              // Program Mode cycles through Red Green Blue waiting to read a new card
     }
     else {
-      normalModeOn(); 		// Normal mode, blue Power LED is on, all others are off
-    }
-  }
-  while (!successRead); 	//the program will not go further while you are not getting a successful read
+      normalModeOn();     // Normal mode, blue Power LED is on, all others are off
+    }
+  }
+  while (!successRead);   //the program will not go further while you are not getting a successful read
   if (programMode) {
     if ( isMaster(readCard) ) { //When in program mode check First If master card scanned again to exit program mode
       Serial.println(F("Master Card Scanned"));
@@ -254,11 +254,11 @@
     }
   }
   else {
-    if ( isMaster(readCard)) {  	// If scanned card's ID matches Master Card's ID - enter program mode
+    if ( isMaster(readCard)) {    // If scanned card's ID matches Master Card's ID - enter program mode
       programMode = true;
       Serial.println(F("Hello Master - Entered Program Mode"));
-      int count = EEPROM.read(0); 	// Read the first Byte of EEPROM that
-      Serial.print(F("I have "));    	// stores the number of ID's in EEPROM
+      uint8_t count = EEPROM.read(0);   // Read the first Byte of EEPROM that
+      Serial.print(F("I have "));     // stores the number of ID's in EEPROM
       Serial.print(count);
       Serial.print(F(" record(s) on EEPROM"));
       Serial.println("");
@@ -267,11 +267,11 @@
       Serial.println(F("-----------------------------"));
     }
     else {
-      if ( findID(readCard) ) {	// If not, see if the card is in the EEPROM
+      if ( findID(readCard) ) { // If not, see if the card is in the EEPROM
         Serial.println(F("Welcome, You shall pass"));
-        granted(300);        	// Open the door lock for 300 ms
+        granted(300);         // Open the door lock for 300 ms
       }
-      else {			// If not, show that the ID was not valid
+      else {      // If not, show that the ID was not valid
         Serial.println(F("You shall not pass"));
         denied();
       }
@@ -280,27 +280,27 @@
 }

 /////////////////////////////////////////  Access Granted    ///////////////////////////////////
-void granted (int setDelay) {
-  digitalWrite(blueLed, LED_OFF); 	// Turn off blue LED
-  digitalWrite(redLed, LED_OFF); 	// Turn off red LED
-  digitalWrite(greenLed, LED_ON); 	// Turn on green LED
-  digitalWrite(relay, LOW); 		// Unlock door!
-  delay(setDelay); 					// Hold door lock open for given seconds
-  digitalWrite(relay, HIGH); 		// Relock door
-  delay(1000); 						// Hold green LED on for a second
+void granted ( uint16_t setDelay) {
+  digitalWrite(blueLed, LED_OFF);   // Turn off blue LED
+  digitalWrite(redLed, LED_OFF);  // Turn off red LED
+  digitalWrite(greenLed, LED_ON);   // Turn on green LED
+  digitalWrite(relay, LOW);     // Unlock door!
+  delay(setDelay);          // Hold door lock open for given seconds
+  digitalWrite(relay, HIGH);    // Relock door
+  delay(1000);            // Hold green LED on for a second
 }

 ///////////////////////////////////////// Access Denied  ///////////////////////////////////
 void denied() {
-  digitalWrite(greenLed, LED_OFF); 	// Make sure green LED is off
-  digitalWrite(blueLed, LED_OFF); 	// Make sure blue LED is off
-  digitalWrite(redLed, LED_ON); 	// Turn on red LED
+  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
+  digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
+  digitalWrite(redLed, LED_ON);   // Turn on red LED
   delay(1000);
 }

 ///////////////////////////////////////// Get PICC's UID ///////////////////////////////////
-int getID() {
+uint8_t getID() {
   // Getting ready for Reading PICCs
   if ( ! mfrc522.PICC_IsNewCardPresent()) { //If a new PICC placed to RFID reader continue
     return 0;
@@ -312,7 +312,7 @@
   // I think we should assume every PICC as they have 4 byte UID
   // Until we support 7 byte PICCs
   Serial.println(F("Scanned PICC's UID:"));
-  for (int i = 0; i < 4; i++) {  //
+  for ( uint8_t i = 0; i < 4; i++) {  //
     readCard[i] = mfrc522.uid.uidByte[i];
     Serial.print(readCard[i], HEX);
   }
@@ -338,54 +338,54 @@
     Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?"));
     Serial.println(F("SYSTEM HALTED: Check connections."));
     // Visualize system is halted
-    digitalWrite(greenLed, LED_OFF); 	// Make sure green LED is off
-    digitalWrite(blueLed, LED_OFF); 	// Make sure blue LED is off
-    digitalWrite(redLed, LED_ON); 	// Turn on red LED
+    digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
+    digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
+    digitalWrite(redLed, LED_ON);   // Turn on red LED
     while (true); // do not go further
   }
 }

 ///////////////////////////////////////// Cycle Leds (Program Mode) ///////////////////////////////////
 void cycleLeds() {
-  digitalWrite(redLed, LED_OFF); 	// Make sure red LED is off
-  digitalWrite(greenLed, LED_ON); 	// Make sure green LED is on
-  digitalWrite(blueLed, LED_OFF); 	// Make sure blue LED is off
-  delay(200);
-  digitalWrite(redLed, LED_OFF); 	// Make sure red LED is off
-  digitalWrite(greenLed, LED_OFF); 	// Make sure green LED is off
-  digitalWrite(blueLed, LED_ON); 	// Make sure blue LED is on
-  delay(200);
-  digitalWrite(redLed, LED_ON); 	// Make sure red LED is on
-  digitalWrite(greenLed, LED_OFF); 	// Make sure green LED is off
-  digitalWrite(blueLed, LED_OFF); 	// Make sure blue LED is off
+  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
+  digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
+  digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
+  delay(200);
+  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
+  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
+  digitalWrite(blueLed, LED_ON);  // Make sure blue LED is on
+  delay(200);
+  digitalWrite(redLed, LED_ON);   // Make sure red LED is on
+  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
+  digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
   delay(200);
 }

 //////////////////////////////////////// Normal Mode Led  ///////////////////////////////////
 void normalModeOn () {
-  digitalWrite(blueLed, LED_ON); 	// Blue LED ON and ready to read card
-  digitalWrite(redLed, LED_OFF); 	// Make sure Red LED is off
-  digitalWrite(greenLed, LED_OFF); 	// Make sure Green LED is off
-  digitalWrite(relay, HIGH); 		// Make sure Door is Locked
+  digitalWrite(blueLed, LED_ON);  // Blue LED ON and ready to read card
+  digitalWrite(redLed, LED_OFF);  // Make sure Red LED is off
+  digitalWrite(greenLed, LED_OFF);  // Make sure Green LED is off
+  digitalWrite(relay, HIGH);    // Make sure Door is Locked
 }

 //////////////////////////////////////// Read an ID from EEPROM //////////////////////////////
-void readID( int number ) {
-  int start = (number * 4 ) + 2; 		// Figure out starting position
-  for ( int i = 0; i < 4; i++ ) { 		// Loop 4 times to get the 4 Bytes
-    storedCard[i] = EEPROM.read(start + i); 	// Assign values read from EEPROM to array
+void readID( uint8_t number ) {
+  uint8_t start = (number * 4 ) + 2;    // Figure out starting position
+  for ( uint8_t i = 0; i < 4; i++ ) {     // Loop 4 times to get the 4 Bytes
+    storedCard[i] = EEPROM.read(start + i);   // Assign values read from EEPROM to array
   }
 }

 ///////////////////////////////////////// Add ID to EEPROM   ///////////////////////////////////
 void writeID( byte a[] ) {
-  if ( !findID( a ) ) { 		// Before we write to the EEPROM, check to see if we have seen this card before!
-    int num = EEPROM.read(0); 		// Get the numer of used spaces, position 0 stores the number of ID cards
-    int start = ( num * 4 ) + 6; 	// Figure out where the next slot starts
-    num++; 								// Increment the counter by one
-    EEPROM.write( 0, num ); 		// Write the new count to the counter
-    for ( int j = 0; j < 4; j++ ) { 	// Loop 4 times
-      EEPROM.write( start + j, a[j] ); 	// Write the array values to EEPROM in the right position
+  if ( !findID( a ) ) {     // Before we write to the EEPROM, check to see if we have seen this card before!
+    uint8_t num = EEPROM.read(0);     // Get the numer of used spaces, position 0 stores the number of ID cards
+    uint8_t start = ( num * 4 ) + 6;  // Figure out where the next slot starts
+    num++;                // Increment the counter by one
+    EEPROM.write( 0, num );     // Write the new count to the counter
+    for ( uint8_t j = 0; j < 4; j++ ) {   // Loop 4 times
+      EEPROM.write( start + j, a[j] );  // Write the array values to EEPROM in the right position
     }
     successWrite();
     Serial.println(F("Succesfully added ID record to EEPROM"));
@@ -398,26 +398,26 @@

 ///////////////////////////////////////// Remove ID from EEPROM   ///////////////////////////////////
 void deleteID( byte a[] ) {
-  if ( !findID( a ) ) { 		// Before we delete from the EEPROM, check to see if we have this card!
-    failedWrite(); 			// If not
+  if ( !findID( a ) ) {     // Before we delete from the EEPROM, check to see if we have this card!
+    failedWrite();      // If not
     Serial.println(F("Failed! There is something wrong with ID or bad EEPROM"));
   }
   else {
-    int num = EEPROM.read(0); 	// Get the numer of used spaces, position 0 stores the number of ID cards
-    int slot; 			// Figure out the slot number of the card
-    int start;			// = ( num * 4 ) + 6; // Figure out where the next slot starts
-    int looping; 		// The number of times the loop repeats
-    int j;
-    int count = EEPROM.read(0); // Read the first Byte of EEPROM that stores number of cards
-    slot = findIDSLOT( a ); 	// Figure out the slot number of the card to delete
+    uint8_t num = EEPROM.read(0);   // Get the numer of used spaces, position 0 stores the number of ID cards
+    uint8_t slot;       // Figure out the slot number of the card
+    uint8_t start;      // = ( num * 4 ) + 6; // Figure out where the next slot starts
+    uint8_t looping;    // The number of times the loop repeats
+    uint8_t j;
+    uint8_t count = EEPROM.read(0); // Read the first Byte of EEPROM that stores number of cards
+    slot = findIDSLOT( a );   // Figure out the slot number of the card to delete
     start = (slot * 4) + 2;
     looping = ((num - slot) * 4);
-    num--; 			// Decrement the counter by one
-    EEPROM.write( 0, num ); 	// Write the new count to the counter
-    for ( j = 0; j < looping; j++ ) { 				// Loop the card shift times
-      EEPROM.write( start + j, EEPROM.read(start + 4 + j)); 	// Shift the array values to 4 places earlier in the EEPROM
-    }
-    for ( int k = 0; k < 4; k++ ) { 				// Shifting loop
+    num--;      // Decrement the counter by one
+    EEPROM.write( 0, num );   // Write the new count to the counter
+    for ( j = 0; j < looping; j++ ) {         // Loop the card shift times
+      EEPROM.write( start + j, EEPROM.read(start + 4 + j));   // Shift the array values to 4 places earlier in the EEPROM
+    }
+    for ( uint8_t k = 0; k < 4; k++ ) {         // Shifting loop
       EEPROM.write( start + j + k, 0);
     }
     successDelete();
@@ -427,43 +427,43 @@

 ///////////////////////////////////////// Check Bytes   ///////////////////////////////////
 boolean checkTwo ( byte a[], byte b[] ) {
-  if ( a[0] != NULL ) 			// Make sure there is something in the array first
-    match = true; 			// Assume they match at first
-  for ( int k = 0; k < 4; k++ ) { 	// Loop 4 times
-    if ( a[k] != b[k] ) 		// IF a != b then set match = false, one fails, all fail
+  if ( a[0] != 0 )      // Make sure there is something in the array first
+    match = true;       // Assume they match at first
+  for ( uint8_t k = 0; k < 4; k++ ) {   // Loop 4 times
+    if ( a[k] != b[k] )     // IF a != b then set match = false, one fails, all fail
       match = false;
   }
-  if ( match ) { 			// Check to see if if match is still true
-    return true; 			// Return true
+  if ( match ) {      // Check to see if if match is still true
+    return true;      // Return true
   }
   else  {
-    return false; 			// Return false
+    return false;       // Return false
   }
 }

 ///////////////////////////////////////// Find Slot   ///////////////////////////////////
-int findIDSLOT( byte find[] ) {
-  int count = EEPROM.read(0); 			// Read the first Byte of EEPROM that
-  for ( int i = 1; i <= count; i++ ) { 		// Loop once for each EEPROM entry
-    readID(i); 								// Read an ID from EEPROM, it is stored in storedCard[4]
-    if ( checkTwo( find, storedCard ) ) { 	// Check to see if the storedCard read from EEPROM
+uint8_t findIDSLOT( byte find[] ) {
+  uint8_t count = EEPROM.read(0);       // Read the first Byte of EEPROM that
+  for ( uint8_t i = 1; i <= count; i++ ) {    // Loop once for each EEPROM entry
+    readID(i);                // Read an ID from EEPROM, it is stored in storedCard[4]
+    if ( checkTwo( find, storedCard ) ) {   // Check to see if the storedCard read from EEPROM
       // is the same as the find[] ID card passed
-      return i; 				// The slot number of the card
-      break; 					// Stop looking we found it
+      return i;         // The slot number of the card
+      break;          // Stop looking we found it
     }
   }
 }

 ///////////////////////////////////////// Find ID From EEPROM   ///////////////////////////////////
 boolean findID( byte find[] ) {
-  int count = EEPROM.read(0);			// Read the first Byte of EEPROM that
-  for ( int i = 1; i <= count; i++ ) {  	// Loop once for each EEPROM entry
-    readID(i); 					// Read an ID from EEPROM, it is stored in storedCard[4]
-    if ( checkTwo( find, storedCard ) ) {  	// Check to see if the storedCard read from EEPROM
+  uint8_t count = EEPROM.read(0);     // Read the first Byte of EEPROM that
+  for ( uint8_t i = 1; i <= count; i++ ) {    // Loop once for each EEPROM entry
+    readID(i);          // Read an ID from EEPROM, it is stored in storedCard[4]
+    if ( checkTwo( find, storedCard ) ) {   // Check to see if the storedCard read from EEPROM
       return true;
-      break; 	// Stop looking we found it
-    }
-    else {  	// If not, return false
+      break;  // Stop looking we found it
+    }
+    else {    // If not, return false
     }
   }
   return false;
@@ -472,57 +472,57 @@
 ///////////////////////////////////////// Write Success to EEPROM   ///////////////////////////////////
 // Flashes the green LED 3 times to indicate a successful write to EEPROM
 void successWrite() {
-  digitalWrite(blueLed, LED_OFF); 	// Make sure blue LED is off
-  digitalWrite(redLed, LED_OFF); 	// Make sure red LED is off
-  digitalWrite(greenLed, LED_OFF); 	// Make sure green LED is on
-  delay(200);
-  digitalWrite(greenLed, LED_ON); 	// Make sure green LED is on
-  delay(200);
-  digitalWrite(greenLed, LED_OFF); 	// Make sure green LED is off
-  delay(200);
-  digitalWrite(greenLed, LED_ON); 	// Make sure green LED is on
-  delay(200);
-  digitalWrite(greenLed, LED_OFF); 	// Make sure green LED is off
-  delay(200);
-  digitalWrite(greenLed, LED_ON); 	// Make sure green LED is on
+  digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
+  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
+  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is on
+  delay(200);
+  digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
+  delay(200);
+  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
+  delay(200);
+  digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
+  delay(200);
+  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
+  delay(200);
+  digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
   delay(200);
 }

 ///////////////////////////////////////// Write Failed to EEPROM   ///////////////////////////////////
 // Flashes the red LED 3 times to indicate a failed write to EEPROM
 void failedWrite() {
-  digitalWrite(blueLed, LED_OFF); 	// Make sure blue LED is off
-  digitalWrite(redLed, LED_OFF); 	// Make sure red LED is off
-  digitalWrite(greenLed, LED_OFF); 	// Make sure green LED is off
-  delay(200);
-  digitalWrite(redLed, LED_ON); 	// Make sure red LED is on
-  delay(200);
-  digitalWrite(redLed, LED_OFF); 	// Make sure red LED is off
-  delay(200);
-  digitalWrite(redLed, LED_ON); 	// Make sure red LED is on
-  delay(200);
-  digitalWrite(redLed, LED_OFF); 	// Make sure red LED is off
-  delay(200);
-  digitalWrite(redLed, LED_ON); 	// Make sure red LED is on
+  digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
+  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
+  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
+  delay(200);
+  digitalWrite(redLed, LED_ON);   // Make sure red LED is on
+  delay(200);
+  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
+  delay(200);
+  digitalWrite(redLed, LED_ON);   // Make sure red LED is on
+  delay(200);
+  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
+  delay(200);
+  digitalWrite(redLed, LED_ON);   // Make sure red LED is on
   delay(200);
 }

 ///////////////////////////////////////// Success Remove UID From EEPROM  ///////////////////////////////////
 // Flashes the blue LED 3 times to indicate a success delete to EEPROM
 void successDelete() {
-  digitalWrite(blueLed, LED_OFF); 	// Make sure blue LED is off
-  digitalWrite(redLed, LED_OFF); 	// Make sure red LED is off
-  digitalWrite(greenLed, LED_OFF); 	// Make sure green LED is off
-  delay(200);
-  digitalWrite(blueLed, LED_ON); 	// Make sure blue LED is on
-  delay(200);
-  digitalWrite(blueLed, LED_OFF); 	// Make sure blue LED is off
-  delay(200);
-  digitalWrite(blueLed, LED_ON); 	// Make sure blue LED is on
-  delay(200);
-  digitalWrite(blueLed, LED_OFF); 	// Make sure blue LED is off
-  delay(200);
-  digitalWrite(blueLed, LED_ON); 	// Make sure blue LED is on
+  digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
+  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
+  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
+  delay(200);
+  digitalWrite(blueLed, LED_ON);  // Make sure blue LED is on
+  delay(200);
+  digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
+  delay(200);
+  digitalWrite(blueLed, LED_ON);  // Make sure blue LED is on
+  delay(200);
+  digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
+  delay(200);
+  digitalWrite(blueLed, LED_ON);  // Make sure blue LED is on
   delay(200);
 }


Delete delete confusing demo.

Delete delete confusing demo.

- standard demoreeel works on ESP32 now
- https://github.com/FastLED/FastLED/issues/711 says this demo worked
  badly.
- https://github.com/FastLED/FastLED/issues/713 says it's incompatible
  with Wifi.

--- examples/DemoReelESP32/DemoReelESP32.ino
+++ examples/DemoReelESP32/DemoReelESP32.ino
@@ -1,181 +0,0 @@
-#include "FastLED.h"
-
-FASTLED_USING_NAMESPACE
-
-// FastLED "100-lines-of-code" demo reel, showing just a few
-// of the kinds of animation patterns you can quickly and easily
-// compose using FastLED.
-//
-// This example also shows one easy way to define multiple
-// animations patterns and have them automatically rotate.
-//
-// -Mark Kriegsman, December 2014
-
-#if defined(FASTLED_VERSION) && (FASTLED_VERSION < 3001000)
-#warning "Requires FastLED 3.1 or later; check github for latest code."
-#endif
-
-#define DATA_PIN    12
-//#define CLK_PIN   4
-#define LED_TYPE    WS2811
-#define COLOR_ORDER GRB
-#define NUM_LEDS    27
-CRGB leds[NUM_LEDS];
-
-#define BRIGHTNESS          60
-#define FRAMES_PER_SECOND  120
-
-// -- The core to run FastLED.show()
-#define FASTLED_SHOW_CORE 0
-
-// -- Task handles for use in the notifications
-static TaskHandle_t FastLEDshowTaskHandle = 0;
-static TaskHandle_t userTaskHandle = 0;
-
-/** show() for ESP32
- *  Call this function instead of FastLED.show(). It signals core 0 to issue a show,
- *  then waits for a notification that it is done.
- */
-void FastLEDshowESP32()
-{
-    if (userTaskHandle == 0) {
-        // -- Store the handle of the current task, so that the show task can
-        //    notify it when it's done
-        userTaskHandle = xTaskGetCurrentTaskHandle();
-
-        // -- Trigger the show task
-        xTaskNotifyGive(FastLEDshowTaskHandle);
-
-        // -- Wait to be notified that it's done
-        const TickType_t xMaxBlockTime = pdMS_TO_TICKS( 200 );
-        ulTaskNotifyTake(pdTRUE, xMaxBlockTime);
-        userTaskHandle = 0;
-    }
-}
-
-/** show Task
- *  This function runs on core 0 and just waits for requests to call FastLED.show()
- */
-void FastLEDshowTask(void *pvParameters)
-{
-    // -- Run forever...
-    for(;;) {
-        // -- Wait for the trigger
-        ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
-
-        // -- Do the show (synchronously)
-        FastLED.show();
-
-        // -- Notify the calling task
-        xTaskNotifyGive(userTaskHandle);
-    }
-}
-
-void setup() {
-  delay(3000); // 3 second delay for recovery
-  Serial.begin(115200);
-
-  // tell FastLED about the LED strip configuration
-  FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
-  //FastLED.addLeds<LED_TYPE,DATA_PIN,CLK_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
-
-  // set master brightness control
-  FastLED.setBrightness(BRIGHTNESS);
-
-    int core = xPortGetCoreID();
-    Serial.print("Main code running on core ");
-    Serial.println(core);
-
-    // -- Create the FastLED show task
-    xTaskCreatePinnedToCore(FastLEDshowTask, "FastLEDshowTask", 2048, NULL, 2, &FastLEDshowTaskHandle, FASTLED_SHOW_CORE);
-}
-
-
-// List of patterns to cycle through.  Each is defined as a separate function below.
-typedef void (*SimplePatternList[])();
-SimplePatternList gPatterns = { rainbow, rainbowWithGlitter, confetti, sinelon, juggle, bpm };
-
-uint8_t gCurrentPatternNumber = 0; // Index number of which pattern is current
-uint8_t gHue = 0; // rotating "base color" used by many of the patterns
-
-void loop()
-{
-  // Call the current pattern function once, updating the 'leds' array
-  gPatterns[gCurrentPatternNumber]();
-
-  // send the 'leds' array out to the actual LED strip
-  FastLEDshowESP32();
-  // FastLED.show();
-  // insert a delay to keep the framerate modest
-  FastLED.delay(1000/FRAMES_PER_SECOND);
-
-  // do some periodic updates
-  EVERY_N_MILLISECONDS( 20 ) { gHue++; } // slowly cycle the "base color" through the rainbow
-  EVERY_N_SECONDS( 10 ) { nextPattern(); } // change patterns periodically
-}
-
-#define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0]))
-
-void nextPattern()
-{
-  // add one to the current pattern number, and wrap around at the end
-  gCurrentPatternNumber = (gCurrentPatternNumber + 1) % ARRAY_SIZE( gPatterns);
-}
-
-void rainbow()
-{
-  // FastLED's built-in rainbow generator
-  fill_rainbow( leds, NUM_LEDS, gHue, 7);
-}
-
-void rainbowWithGlitter()
-{
-  // built-in FastLED rainbow, plus some random sparkly glitter
-  rainbow();
-  addGlitter(80);
-}
-
-void addGlitter( fract8 chanceOfGlitter)
-{
-  if( random8() < chanceOfGlitter) {
-    leds[ random16(NUM_LEDS) ] += CRGB::White;
-  }
-}
-
-void confetti()
-{
-  // random colored speckles that blink in and fade smoothly
-  fadeToBlackBy( leds, NUM_LEDS, 10);
-  int pos = random16(NUM_LEDS);
-  leds[pos] += CHSV( gHue + random8(64), 200, 255);
-}
-
-void sinelon()
-{
-  // a colored dot sweeping back and forth, with fading trails
-  fadeToBlackBy( leds, NUM_LEDS, 20);
-  int pos = beatsin16( 13, 0, NUM_LEDS-1 );
-  leds[pos] += CHSV( gHue, 255, 192);
-}
-
-void bpm()
-{
-  // colored stripes pulsing at a defined Beats-Per-Minute (BPM)
-  uint8_t BeatsPerMinute = 62;
-  CRGBPalette16 palette = PartyColors_p;
-  uint8_t beat = beatsin8( BeatsPerMinute, 64, 255);
-  for( int i = 0; i < NUM_LEDS; i++) { //9948
-    leds[i] = ColorFromPalette(palette, gHue+(i*2), beat-gHue+(i*10));
-  }
-}
-
-void juggle() {
-  // eight colored dots, weaving in and out of sync with each other
-  fadeToBlackBy( leds, NUM_LEDS, 20);
-  byte dothue = 0;
-  for( int i = 0; i < 8; i++) {
-    leds[beatsin16( i+7, 0, NUM_LEDS-1 )] |= CHSV(dothue, 200, 255);
-    dothue += 32;
-  }
-}
-


Cleanup.

Cleanup.

--- examples/LCD/CosaST7565P/CosaST7565P.ino
+++ examples/LCD/CosaST7565P/CosaST7565P.ino
@@ -58,9 +58,9 @@
   lcd.putchar('\f');
   trace << PSTR("CosaST7565P: started\n");
   lcd.set_cursor(0, 1);
-  trace << PSTR("====================");
+  trace << PSTR("====================\n");
   INFO("saved = %d", saved);
-  lcd.set_text_mode(saved);
+  TRACE(lcd.set_text_mode(saved));
   SLEEP(2);

   // Use the trace iostream onto the LCD with output operator
@@ -85,9 +85,9 @@
   trace.print(&lcd, sizeof(lcd) - 1, IOStream::hex, 5);
   SLEEP(2);

-  // Dump characters in system font; two pages, 64 characters each
+  // Dump characters in system font
   lcd.putchar('\f');
-  for (uint8_t c = 0; c < 64; c++) {
+  for (uint8_t c = 0; c < 128; c++) {
     trace << (char) (((c == '\n') || (c == '\f') || (c == '\b')) ? ' ' : c);
   }
   SLEEP(2);


power meter client.loop

power meter client.loop

--- _06-power_meter/_06-power_meter.ino
+++ _06-power_meter/_06-power_meter.ino
@@ -7,8 +7,8 @@
 #define _IS_MY_HOME
 // WIFI
 #ifdef _IS_MY_HOME
-//#include "/usr/local/src/ap_settingii.h"
-#include "/usr/local/src/ap_setting.h"
+#include "/usr/local/src/ap_settingii.h"
+//#include "/usr/local/src/ap_setting.h"
 #else
 #include "ap_setting.h"
 #endif
@@ -230,7 +230,7 @@
           lastReconnectAttempt = 0;
         }
       }
-    }
+    }
   } else {
     wifi_connect();
   }
@@ -238,8 +238,6 @@
   VIrms = emon1.calcIrms(1480) * 220.0;
   ave.push(VIrms);
   average = ave.mean();
-
-  client.loop();

   if ( revMills > 600 ) {
     revValue = (float(( 3600  * 1000 ) / ( 600 * float(revMills) ) ) * 1000);
@@ -300,7 +298,7 @@
     sentMills = millis();
   }
   client.loop();
-  //delay(50);
+  delay(50);

 }

@@ -316,6 +314,8 @@
   }
   */

+  client.loop();
+
   if (client.connected()) {
     if (DEBUG_PRINT) {
       Serial.print("Sending payload: ");


Delete unused variables

Delete unused variables

--- Programmer.ino
+++ Programmer.ino
@@ -84,8 +84,6 @@
 hexRecordStruct hexRecord;  // Decoded hex data

 size_t numChars;   // Serial characters received counter
-byte fsr;          // Flash status register buffer
-byte spi_data;     // SPI data transfer buffer
 byte infopage[37]; // Buffer for storing InfoPage content


add comma

add comma

--- cmdRHsens/src/sketch.ino
+++ cmdRHsens/src/sketch.ino
@@ -93,6 +93,7 @@
         Serial.print(", ");
         ReturnedValue = dht.computeDewPoint( t, h );
         Serial.print(ReturnedValue);        // AverageValue
+        Serial.print(", ");
         ReturnedValue = dht.computeDewPoint2( t, h );
         Serial.print(ReturnedValue);        // AverageValue
         break;


Add unipolar code

Add unipolar code

--- hardware/steppers/steppers.ino
+++ hardware/steppers/steppers.ino
@@ -33,3 +33,63 @@
   motor.step(250, FORWARD, MICROSTEP);
   motor.step(250, BACKWARD, MICROSTEP);
 }
+
+
+
+
+/*
+Version that works for unipolor motors, but I wounder if there is a function for this as well.
+AF_DCMotor motor1(1, MOTOR12_64KHZ); // create motor #1, 64KHz pwm
+AF_DCMotor motor2(2, MOTOR12_64KHZ); // create motor #2, 64KHz pwm
+AF_DCMotor motor3(3, MOTOR12_64KHZ); // create motor #2, 64KHz pwm
+AF_DCMotor motor4(4, MOTOR12_64KHZ); // create motor #2, 64KHz pwm
+int d;
+
+void setup() {
+  Serial.begin(250000);
+  motor1.setSpeed(255);
+  motor2.setSpeed(255);
+  motor3.setSpeed(255);
+  motor4.setSpeed(255);
+  d = 4;
+}
+
+void loop() {
+
+  motor1.run(FORWARD);      // turn it on going forward
+  delay(d);
+  motor4.run(RELEASE);      // turn it on going forward
+  delay(d);
+  motor2.run(FORWARD);      // turn it on going forward
+  delay(d);
+  motor1.run(RELEASE);      // turn it on going forward
+  delay(d);
+  motor3.run(FORWARD);      // turn it on going forward
+  delay(d);
+  motor2.run(RELEASE);      // turn it on going forward
+  delay(d);
+  motor4.run(FORWARD);      // turn it on going forward
+  delay(d);
+  motor3.run(RELEASE);      // turn it on going forward
+  delay(d);
+
+
+  /*
+  delay(10);
+  motor1.run(RELEASE);      // turn it on going forward
+  motor2.run(FORWARD);      // turn it on going forward
+  delay(10);
+  motor1.run(BACKWARD);      // turn it on going forward
+  motor2.run(RELEASE);      // turn it on going forward
+  delay(10);
+  motor1.run(RELEASE);      // turn it on going forward
+  motor2.run(BACKWARD);      // turn it on going forward
+  delay(10);
+  */
+}
+*/
+
+
+
+
+


making sure height measurement is accurate and up-to-date

--- telemetryBox.ino
+++ telemetryBox.ino
@@ -24,9 +24,12 @@
 float distance;
 unsigned long duration;
 float waterHeight;
+float waterHeightSum;
 //################### update these vars ###################
 float totalDistance = 64; // the distance from the sensor to the bottom of the water tank
 //################### update these vars ###################
+unsigned long lastUS = 0;
+unsigned long USmeasureTime = 1000; // measure every second

 // photocell
 float lightIntensity;
@@ -100,6 +103,10 @@
         // The Photon will stay on unless the battery is less than 75% full, or if the pump is running.
         // If the battery is low, it will stay on if we've told it we want to update the firmware, until that times out (updateTimeout)
         // It will stay on no matter what for a time we set, stored in the variable communicationTimeout
+
+		if (millis() - lastUS > USmeasureTime) { // measure waterHeight more frequently
+            measureUS();
+        }
         if (millis() - lastMeasureTime > measureInterval) {
             doTelemetry();
         }
@@ -113,6 +120,20 @@
                 System.sleep(SLEEP_MODE_DEEP, wakeUpTimeoutShort);
             }
     }
+}
+
+void measureUS() {
+    // the pulseIn from the sensor needs to be read often, otherwise it gets backed up with old measurements
+    // perhaps using the analog signal would be better
+    waterHeight = 0;
+    waterHeight2 = 0;
+    for (int i = 0; i < 100; i++) {
+        duration = pulseIn(A0, HIGH);
+        distance = duration / uSperInch; // in inches
+        waterHeightSum += totalDistance - distance;
+        delay(50);
+    }
+    waterHeight = waterHeightSum/100;
 }

 void eventHandler(String event, String data)
@@ -140,9 +161,6 @@
     Particle.publish(eventPrefix + "/waterTankSensor/online", "true");

     // water height
-    duration = pulseIn(A0, HIGH);
-    distance = duration / uSperInch; // in inches
-    waterHeight = totalDistance - distance;
     ThingSpeak.setField(1, waterHeight);

 	Particle.publish(eventPrefix + "/waterTankSensor/waterHeight", String(waterHeight));


remove my_devices arg in subscribe

remove my_devices arg in subscribe

MY_DEVICES wasn't working for me...bug

--- telemetryBox.ino
+++ telemetryBox.ino
@@ -91,8 +91,8 @@

     ThingSpeak.begin(client);

-	Particle.subscribe(eventPrefix + "/waterTankSensor/update", eventHandler); // MY_DEVICES doesn't allow publishes from the cloud API
-	Particle.subscribe(eventPrefix + "/waterTankPump/pumpOn", eventHandler, MY_DEVICES);
+	Particle.subscribe(eventPrefix + "/waterTankSensor/update", eventHandler);
+	Particle.subscribe(eventPrefix + "/waterTankPump/pumpOn", eventHandler);
     Particle.publish(eventPrefix + "/waterTankSensor/online", "true"); // subscribe to this with the API like: curl https://api.particle.io/v1/devices/events/temp?access_token=1234
     bootupStartTime = millis();
 	measureUS();
@@ -190,4 +190,4 @@

     ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
     lastMeasureTime = millis();
-}+}


Refactor: Clean up embedded test code.

Refactor: Clean up embedded test code.

--- test/ino-zmtp-test.ino
+++ test/ino-zmtp-test.ino
@@ -2,21 +2,48 @@

 SYSTEM_MODE(MANUAL);

-void setup() {
+void waitUntilReady(ZMTPSocket &socket) {
+  System.waitCondition(
+      [&]() {
+        // Removing this will crash the application, as socket.ready()
+        // returns true, but socket.recv() won't agree.
+        delay(100);
+        socket.update();
+        return socket.ready();
+      },
+      5000);
+}
+
+zmtp_frame_t *waitUntilRecv(ZMTPSocket &socket) {
+  waitUntilReady(socket);
+
+  zmtp_frame_t *frame = NULL;
+  unsigned long startTime = millis();
+  do {
+    socket.update();
+    frame = socket.recv();
+  } while (startTime - millis() < 5000 && !frame);
+
+  return frame;
+}
+
+void enableWiFi() {
   WiFi.on();
   WiFi.connect();
   waitUntil(WiFi.ready);
+
+  // Particle.process is required to acquire an IP address.
   Particle.process();

   Serial.print("SSID: ");
   Serial.println(WiFi.SSID());
   Serial.print("IP Address: ");
   Serial.println(WiFi.localIP());
+}

+void runDealerTest(uint8_t *address) {
   ZMTPSocket dealer(DEALER);

-  // uint8_t address[4] = { 192, 168, 29, 198 };
-  uint8_t address[4] = {172, 20, 10, 3};
   Serial.printf("Connecting to: %i.%i.%i.%i\n", address[0], address[1],
                 address[2], address[3]);
   dealer.connect(address, 1234);
@@ -24,15 +51,7 @@
   uint8_t identity[6] = {'P', 'h', 'o', 't', 'o', 'n'};
   dealer.setIdentity(identity, 6);

-  int tries = 0;
-  while (!dealer.ready()) {
-    Serial.println("Not ready yet.");
-    if (++tries > 5) {
-      end();
-    }
-    delay(1000);
-    dealer.update();
-  }
+  waitUntilReady(dealer);

   {
     uint8_t data[5] = {'H', 'e', 'l', 'l', 'o'};
@@ -48,30 +67,14 @@
     dealer.send(frame);
     zmtp_frame_destroy(&frame);
   }
+}

+void runRouterTest() {
   ZMTPSocket router(ROUTER);

   router.bind(1235);

-  tries = 0;
-  while (!router.ready()) {
-    Serial.println("Not ready yet.");
-    if (++tries > 5) {
-      end();
-    }
-    delay(1000);
-    router.update();
-  }
-
-  tries = 0;
-  zmtp_frame_t *question = NULL;
-  while (!(question = router.recv())) {
-    Serial.println("No messages yet.");
-    if (++tries > 5) {
-      end();
-    }
-    delay(1000);
-  }
+  zmtp_frame_t *question = waitUntilRecv(router);

   // TODO(schoon) - Receive identity frame first.
   // HACK(schoon) - The zmtp_frame API doesn't tell us about framing, so
@@ -92,7 +95,17 @@
     router.send(frame);
     zmtp_frame_destroy(&frame);
   }
+}

+void setup() {
+  enableWiFi();
+
+  // uint8_t address[4] = { 192, 168, 29, 198 };
+  uint8_t address[4] = {172, 20, 10, 3};
+  runDealerTest(address);
+  runRouterTest();
+
+  // Allow time for network to catch up before we hard disconnect.
   delay(1000);

   end();


fixed the sensor swap

fixed the sensor swap

--- arduino/FishTankApp/FishTankApp.ino
+++ arduino/FishTankApp/FishTankApp.ino
@@ -43,17 +43,17 @@
   }

   // grab address
-  if (!sensors.getAddress(ambientAddress, 0)) {
+  if (!sensors.getAddress(tankAddress, 0)) {
     if(DEBUG) Serial.println("Unable to find address for Device 0");
   }
-  if (!sensors.getAddress(tankAddress, 1)) {
-    if(DEBUG) Serial.println("Unable to find address for Device 0");
+  if (!sensors.getAddress(ambientAddress, 1)) {
+    if(DEBUG) Serial.println("Unable to find address for Device 1");
   }
   if(DEBUG) {
     Serial.print("Addresses: ");
+    printAddress(tankAddress);
+    Serial.print(", ");
     printAddress(ambientAddress);
-    Serial.print(", ");
-    printAddress(tankAddress);
     Serial.println();
   }


add exponential random backoff time

add exponential random backoff time

--- arduino_slave_sensor/Temp_probe.ino
+++ arduino_slave_sensor/Temp_probe.ino
@@ -1,5 +1,6 @@
 #include <LowPower.h>
 #include <DHT.h>
+#include <math.h>

 #define DHTPIN 2
@@ -62,6 +63,8 @@
     byte t_b;
     h_b = (byte) h;
     t_b = (byte) t;
+		short retry = 0;
+		unsigned int wait_time;

     digitalWrite(DHTALIM, LOW);

@@ -69,9 +72,14 @@
       Serial.println("Failed to read from DHT sensor!");
     }
     else {
-      while (sendData(t_b, h_b) != mote_addr)
+      while ((sendData(t_b, h_b) != mote_addr) && (retry < 5))
       {
-        delay(50);
+        wait_time = random(2000 * pow(2, retry));
+				retry++;
+				Serial.print("Will wait ");
+				Serial.print(wait_time);
+				Serial.println("ms before resend.");
+        delay(wait_time);
       }
     }
     digitalWrite(TRANSCEIVERALIM, LOW);


added relay control

added relay control

--- beanfiles/coffeebean/coffeebean.ino
+++ beanfiles/coffeebean/coffeebean.ino
@@ -1,6 +1,6 @@
 #define BREW_TIME 240000 //4 minutes
 #define HEAT_TIME 1800000 //30 minutes
-
+#define COFFEE_PIN 0
 typedef enum
 {
   COFFEE_START = '1',
@@ -19,6 +19,8 @@
 void setup() {
   Bean.enableWakeOnConnect(true);
   Bean.setBeanName("coffeebean");
+  pinMode(COFFEE_PIN, OUTPUT);
+  digitalWrite(COFFEE_PIN, LOW);
   delay(5000);
 }

@@ -28,6 +30,7 @@
   bool isConnected = Bean.getConnectionState();
   if(isConnected || isCoffeeStarted)
   {
+
     if(Serial.available())
     {
       char readIn = Serial.read();
@@ -42,6 +45,7 @@
             //trigger relay
             coffeeStartTime = millis();
             curState = COFFEE_BREW;
+            digitalWrite(COFFEE_PIN, HIGH);
           }

           Serial.write(curState);//coffee is brewing
@@ -73,6 +77,7 @@
         Serial.write(COFFEE_OFF);
         curState = COFFEE_OFF;
         Bean.disconnect();
+        digitalWrite(COFFEE_PIN, LOW);
         //disable relay
       }
     }
@@ -83,6 +88,5 @@
     delay(1000);
     Bean.setLed(0,0,0);
     Bean.sleep(0xFFFFFF);
-
   }
 }


Moving from toggle to state.

Moving from toggle to state.

--- receiver/receiver.ino
+++ receiver/receiver.ino
@@ -180,9 +180,7 @@
       else
         printf("failed\n\r");
       radio.startListening();
-      if ( sensor_state ) {
-        led_state ^= sensor_state;
-      }
+      led_state = sensor_state;
       digitalWrite(led_pin, led_state);
     }

@@ -210,11 +208,8 @@
         printf("Got buttons\n\r");

         // For each button, if the button now on, then toggle the LED
-        if ( sensor_state )
-        {
-          led_state ^= sensor_state;
-          digitalWrite(led_pin, led_state);
-        }
+        led_state = sensor_state;
+        digitalWrite(led_pin, led_state);
       }
     }
   }


Added some palettes and a question

Added some palettes and a question

--- super_freq/super_freq.ino
+++ super_freq/super_freq.ino
@@ -31,7 +31,7 @@
 float frequency;  // only used for debugging

 // LEDeez
-int nLEDs = 32;  // Number of RGB LEDs in strand
+int nLEDs = 160;  // Number of RGB LEDs in strand
 byte max_brightness = 127;  // LED intensity max is 127
 byte brightness;  // where LED brightness is stored (based on dB level)

@@ -67,7 +67,7 @@
 byte palette_color_count = 24;

 // each palette is 24 colors, all are stored in the same array
-const struct Color palettes[48] PROGMEM = {
+const struct Color palettes[148] PROGMEM = {
     // 1st palette: full spectrum of colors
     {  25,   0, 100 },  // indigo
     {   0,   0, 100 },  // blue
@@ -118,7 +118,112 @@
     { 100, 100, 100 },  // white hot
     { 100, 100, 100 },  // white hot
     { 100, 100, 100 },  // white hot
-    { 100, 100, 100 }   // white hot
+    { 100, 100, 100 },   // white hot
+
+     // 3rd palette: Blue Orange, hints of white hot and red
+    {   0,   0, 100 },  // blue
+    {   0,   0, 100 },  // blue
+    {   0,   0, 100 },  // blue
+    {   0,   0, 100 },  // blue
+    { 100,  50,   0 },  // orange
+    { 100,  50,   0 },  // orange
+    { 100,  50,   0 },  // orange
+    { 100,  50,   0 },  // orange
+    {   0,   0, 100 },  // blue
+    {   0,   0, 100 },  // blue
+    { 100,  50,   0 },  // orange
+    { 100,  50,   0 },  // orange
+    {   0,   0, 100 },  // blue
+    {   0,   0, 100 },  // blue
+    { 100,  50,   0 },  // orange
+    {   0,   0, 100 },  // blue
+    { 100,  50,   0 },  // orange
+    {   0,   0, 100 },  // blue
+    { 100,  50,   0 },  // orange
+    {   0,   0, 100 },  // blue
+    { 100,  50,   0 },  // orange
+    { 100,  50,   0 },  // orange
+    {   0,   0, 100 },  // blue
+    { 100,  50,   0 },  // orange
+
+        // 4th palette: brights, less yellows
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+    { 100,  10, 100 },  // hot purple
+
+    // 5th palette: Rat Fink
+    {   0, 100,   0 },  // green
+    {   0, 100,   0 },  // green
+    {   0, 100,   0 },  // green
+    {   0, 100,   0 },  // green
+    { 100,   0,  25 },  // pink
+    { 100,   0,  25 },  // pink
+    { 100,   0,  25 },  // pink
+    { 100,   0,  25 },  // pink
+    {   0, 100,   0 },  // green
+    { 100,   0,  25 },  // pink
+    {   0, 100,   0 },  // green
+    {   0, 100,   0 },  // green
+    { 100,   0,  25 },  // pink
+    { 100,   0,  25 },  // pink
+    { 100,   0,  25 },  // pink
+    {   0, 100,   0 },  // green
+    { 100,   0,  25 },  // pink
+    {   0, 100,   0 },  // green
+    { 100,   0,  25 },  // pink
+    {   0, 100,   0 },  // green
+    { 100,   0,  25 },  // pink
+    { 100,   0,  25 },  // pink
+    {   0, 100,   0 },  // green
+    { 100,   0,  25 },  // pink
+
+    // 6th palette: Simply Red.  WHY ARE THERE OTHER COLORS PRESENT?
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 },  // red
+    { 100,   0,   0 }   // red
+
 };

 Color color_palette[24];


Add line detection fixes to lindukas

Add line detection fixes to lindukas

--- lindukas/lindukas.ino
+++ lindukas/lindukas.ino
@@ -18,6 +18,7 @@

 //#include "gaz.h"
+uint32_t lineLastSeenTs = 0;

 void setup() {
   sendControl();
@@ -71,6 +72,7 @@

     go();
     button.update();
+    lineLastSeenTs = millis();

 }

@@ -78,7 +80,6 @@
 #define P 4
 uint8_t nonCriticalSteerings = 0;
 uint8_t steerings = 0;
-uint32_t lineLastSeenTs = 0;

 void followTheLine() {
   switch (smalsiukasState) {
@@ -87,6 +88,7 @@
         go();
         smalsiukasState = STATE_FOLLOWING;
         beep();
+        lineLastSeenTs = millis();
       }
       break;
     case STATE_FOLLOWING:
@@ -128,14 +130,6 @@
             }
             mirgalkeOff();
           } else {
-            if (0 == l && millis() - lineLastSeenTs > LINE_SEEN_TIMEOUT) {
-              parkingOn();
-              beeep();
-              delay(500);
-              beeep();
-              stop();
-              smalsiukasState = STATE_STOP;
-            }
           }
         } else if (isRequestTimeout()) {
           Serial.print('T');
@@ -153,6 +147,15 @@
         smalsiukasState = STATE_STOP;
       }

+		if (millis() - lineLastSeenTs > LINE_SEEN_TIMEOUT) {
+		  parkingOn();
+		  beeep();
+		  delay(500);
+		  beeep();
+		  stop();
+		  smalsiukasState = STATE_STOP;
+		}
+
       break;
     case STATE_ERROR:
       break;


Sketch changed for new temperature sensor

--- sketches/Rookvat.ino
+++ sketches/Rookvat.ino
@@ -1,570 +0,0 @@
-
-//Own libraries
-#include <Menu.h>
-#include <RGBLed.h>
-#include <Speaker.h>
-#include <GasValve.h>
-#include <TemperatureSensors.h>
-#include <Logger.h>
-#include <MyTFT.h>
-
-//3rd party libraries
-#include <Encoder.h>
-
-#include <DallasTemperature.h>
-#include <OneWire.h>
-#include <AD595.h>
-
-#include <mmc.h>
-#include <tinyFAT.h>
-
-#include "SPI.h"
-#include <Adafruit_GFX.h>
-#include <Adafruit_ILI9341.h>
-
-#include <DS1307RTC.h>
-#include <Time.h>
-#include <Wire.h>
-
-#include <Servo.h>
-#include <Stepper.h>
-
-
-const int TARGET_TEMP_BARREL = 0;
-const int TARGET_TEMP_MEAT = 1;
-
-const int menuSelectorRE_A = 19;
-const int menuSelectorRE_B = 27;
-
-const int menuButton = 18;
-const int pauseButton = A3;
-
-const int oneWireTempSensors_pin = 3;
-
-const int gasValveMotorRotationCheck_RE_A = A2;
-const int gasValveMotorRotationCheck_RE_B = 38;
-
-const int gasValveMotorA = 23;
-const int gasValveMotorB = 24;
-const int gasValveMotorC = 25;
-const int gasValveMotorD = 26;
-
-const int speaker_pin = 37;
-
-const int led1_R = 12;
-const int led1_G = 11;
-const int led1_B = 10;
-
-const int smokeValveServoPin = 9;
-const int smokeValveMin = 0;
-const int smokeValveMax = 180;
-
-const int smokerRegulationInterval = 60; // Every minute. Hope it is ok.
-
-const int meatTempPin = A4;
-const int barrelTempPin = A5;
-const int barrelTCPin = A6;
-
-const int TFT_CS = 53;
-const int TFT_DC = 49;
-const int TFT_MOSI = 51;
-const int TFT_MISO = 50;
-const int TFT_CLK = 52;
-const int TFT_RST = 48;
-const int SD_CS = 47;
-
-/* Initialize the temperature sensors (DS8B20, NTC, Thermocouple)*/
-TemperatureSensors tempSensors(oneWireTempSensors_pin, barrelTempPin, meatTempPin, barrelTCPin);
-
-/* Initialize the RGB Led */
-RGBLed led1(led1_R,led1_G,led1_B);
-
-/* Initialize the speaker */
-Speaker speaker(speaker_pin);
-
-/* Initialize the Rotary Encoders */
-Encoder menuSelector(menuSelectorRE_A, menuSelectorRE_B);
-Encoder gasValveMotorRotationCheck(gasValveMotorRotationCheck_RE_A, gasValveMotorRotationCheck_RE_B);
-
-/* Initialize the LCD Panel */
-//Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK, TFT_RST, TFT_MISO);
-MyTFT *tft;
-
-/* Initialize the RTC (Real Time Clock) */
-// nothing?!
-
-/* Initialize the gas valve; it uses a rotary encoder to check if the gas valve is at the end */
-GasValve gasValve(&gasValveMotorRotationCheck, gasValveMotorA, gasValveMotorB, gasValveMotorC, gasValveMotorD);
-
-/* Initialize the servo */
-SmokeValve *smokeValve;
-
-/* Initialize the menu */
-Menu *mainMenu = new Menu(menuButton);
-
-/* Initialize the logger to the SD card*/
-Logger logger(SD_CS);
-
-/* Here are all the parameters for the application */
-float target_temp = 30.0; // The target temperature
-int target_temp_location = TARGET_TEMP_BARREL;
-int rooktijd=120; //smoketime in minutes
-
-int current_hour=10;
-int current_minute=30;
-int current_second=30;
-int current_month=2;
-int current_day=3;
-int current_year=2014;
-
-int smoking_started = 0; //Is the barrel up-and-running, or are we in 'setup mode'?
-long encvalue=0; // used for the menu-rotary encoder
-volatile bool wasInSelected=false;
-
-time_t starttime, lastregulation; // times for start and lastregulation
-boolean firstSmokeLoop=true;
-float lasttemp, lasttempdif;
-
-/*
- *Here is all the setup of the project done
- */
-void setup() {
-  // initialize Serial device to support debugging
-  Serial.begin(9600);
-
-  //initialize the LCD
-  tft = new MyTFT(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK, TFT_RST, TFT_MISO);
-  //initialize the menu
-  createMenu();
-
-  //Close the smoke valve with the servo
-  smokeValve = new SmokeValve(smokeValveServoPin, smokeValveMin, smokeValveMax);
-  smokeValve->fullyClose();
-
-  //Close the gasvalve
-  gasValve.fullyClose();
-
-  //blink light to indicate start
-  led1.changeColor(&COLOR_GREEN);
-  delay(100);
-  led1.changeColor(&COLOR_BLUE);
-  delay(100);
-  led1.changeColor(&COLOR_RED);
-  //test speaker
-  speaker.on();
-  delay(20);
-  speaker.off();
-
-  // Initialize the rotary encoder
-  encvalue = menuSelector.read();
-
-  // Initialize the menubutton
-  pinMode(menuButton, INPUT);
-  attachInterrupt(getInterruptForPin(menuButton), bPressed, FALLING);
-
-  // Create a new file
-  logger.createUniqueFileName();
-}
-
-/*
- * This is the main of the arduino application
- */
-void loop() {
-  long gasValvePos, smokeValvePos;
-  float barrelTemp, meatTemp, ambientTemp;
-
-
-  tmElements_t tm;
-
-  long newvalue;
-  bool selected = false;
-  int steps = 0;
-
-  // Get the time from the RTC
-  if (RTC.read(tm)) {
-    current_hour=tm.Hour;
-    current_minute=tm.Minute;
-    current_second=tm.Second;
-    current_month=tm.Month;
-    current_day=tm.Day;
-    current_year=tmYearToCalendar(tm.Year);
-  };
-
-  // Do menu things if necessary
-  mainMenu->display(tft->getTFT());
-  wasInSelected = false;
-  selected=false;
-  while (!selected && !wasInSelected) {
-    newvalue = menuSelector.read();
-    if ((newvalue - encvalue) % 4 != 0) {
-      continue;
-    }
-    if (newvalue > encvalue) {
-      steps = (newvalue - encvalue)/4;
-      for (int i=0;i<steps;i++) {
-        mainMenu->highlightNext();
-      };
-      encvalue=newvalue;
-      selected=true;
-    }
-    else {
-      if (newvalue < encvalue) {
-        steps = (encvalue - newvalue)/4;
-        for (int i=0;i<steps;i++) {
-          mainMenu->highlightPrevious();
-        };
-        encvalue=newvalue;
-        selected=true;
-      }
-      else {
-        delay(100);
-        //the same so wait for a new value
-      }
-    }
-  }
-
-  // Check the temps
-  barrelTemp = tempSensors.getBarrelTemperature();
-  meatTemp = tempSensors.getMeatTemperature();
-  ambientTemp = tempSensors.getAmbientTemperature();
-
-  RTC.read(tm);
-  // display the temps and time at the LCD
-  tft->displayTemps(ambientTemp, meatTemp, barrelTemp, target_temp, target_temp_location == TARGET_TEMP_MEAT);
-  tft->displayTime(&tm);
-//  tft->displayTimeRemaining(seconds_smoking_left, smoking_started);
-
-  // Now check if the smoking is started
-  if (smoking_started) {
-    if (firstSmokeLoop) {
-      logger.writeln("Smoking started");
-      starttime = RTC.get();
-      // now determine the endtime for the smoking.
-      firstSmokeLoop = false;
-      lasttemp = 0;
-      lasttempdif = 0;
-      // Change led to green to indicate that smoking is started
-      led1.changeColor(&COLOR_GREEN);
-    }
-    // Do all the regulating one every x seconds. Else there is to much turning on all the knobs
-    time_t current = RTC.get();
-    if (current - lastregulation > smokerRegulationInterval) {
-
-      // Check the temps
-      barrelTemp = tempSensors.getBarrelTemperature();
-      meatTemp = tempSensors.getMeatTemperature();
-      ambientTemp = tempSensors.getAmbientTemperature();
-      if (ambientTemp > target_temp) {
-        logger.writeln("Error: ambient temperature higher than target temperature. Aborting!");
-        led1.changeColor(&COLOR_MAGENTA);
-        smoking_started = false;
-      }
-      // Get the positions of the gasvalve steppermotor and smoke valve servo
-      gasValvePos = gasValve.getCurrentPosition();
-      smokeValvePos = smokeValve->getCurrentPosition();
-
-      // Also update the LCD display to show the current positions (temps are already done
-      tft->displayValveStatus(smokeValvePos, gasValvePos);
-
-      // Now determine which temperature to use and see what the diff is between the current temp and the target temp
-      float temp = (target_temp_location == TARGET_TEMP_BARREL)?barrelTemp:meatTemp;
-      float tempdif = target_temp - temp;
-
-      // Now write all the logging for later inspection
-      logger.writeLoggingInfo(ambientTemp, meatTemp, barrelTemp, target_temp, target_temp_location, temp, tempdif, lasttempdif, gasValvePos, smokeValvePos);
-
-      // tempdif > 0 betekent dat de temperatuur nog niet bereikt is. Er mag nog doorgestookt worden,
-      // alleen moet als de tempdif bijna bij 0 is wel opgelet worden dat de gaskraan niet meer hoog open blijft.
-
-      if (tempdif > 0) { // is it too cold. but how much? And was it to cold last time?
-        logger.writeln("1: tempdif > 0");
-        if (lasttempdif < 0) { // was it to hot last time?
-          logger.writeln("1.1: lasttempdif < 0");
-          if (tempdif < 1) { // is it just 1 degree to cold? Try to regulate it with the smoke valve
-            logger.writeln("1.1.1: tempdif < 1");
-            smokeValve->close(50); // close it and hope the temp will stabilize
-          } else if (tempdif < 3) { // 3 degrees to cold, but last time it was too hot, so the temp dropped a lot
-            logger.writeln("1.1.2: tempdif < 3");
-            smokeValve->fullyClose(); // close the smokevalve fully.
-            gasValve.open(1); // just 1 step open
-          } else { // more than 3 degrees temp drop in 1 minute. That is really strange.
-            logger.writeln("1.1.3: tempdif >= 3");
-            smokeValve->fullyClose(); // close the smokevalve
-            gasValve.open(3); // turn on the heat
-          }
-        } else { // it was not to hot last time
-          logger.writeln("1.2: lasttempdif >= 0");
-          // now determine how close we are
-          if (tempdif < 5) { // just 5 degrees? Look at the last value, so we know how much it was raised in 1 cycle
-            logger.writeln("1.2.1: tempdif < 5");
-            if (lasttempdif <= tempdif) { // it even got colder?
-              logger.writeln("1.2.1.1: lasttempdif <= tempdif");
-              gasValve.open(1); // open the gas a little bit
-              smokeValve->close(5); // and close the smokevalve;
-            } else if (lasttempdif < 10) { // it was 10 degrees to cold and now 5. So lets temper the fire and hope it will use the restwarmte
-              logger.writeln("1.2.1.2: lasttempdif < 10");
-              if (gasValve.close(5)) { // now fully closed?
-                // do something with the smokevalve? I don't know
-               logger.writeln("1.2.1.2.1: gasvalve.close == true");
-             }
-            } else if (lasttempdif < 20) {
-              logger.writeln("1.2.1.3: lasttempdif < 20");
-
-              // So it was almost 20 degrees in 1 cycle
-              if (gasValve.isFullyClosed()) { // is the gasvalve already closed and it still raised that much?
-               logger.writeln("1.2.1.3.1: gasValve.isFullyClosed()");
-               smokeValve->fullyOpen();
-              } else {
-               logger.writeln("1.2.1.3.2: !gasValve.isFullyClosed()");
-                gasValve.fullyClose(); //
-                smokeValve->open(20);
-              }
-            } else { // more than 20 degrees in one cycle. So vent it and hope the temp will not raise to much
-              logger.writeln("1.2.1.4: lasttempdif >= 20");
-              gasValve.fullyClose();
-              smokeValve->fullyOpen();
-            }
-          } else if (tempdif < 10) { // just 10 degrees to cold
-              logger.writeln("1.2.2: tempdif < 10");
-             if (lasttempdif < 10) { // but last time it was also 10 degrees to cold
-               logger.writeln("1.2.2.1: tempdif < 10");
-               if (gasValve.open(3)) {// turn on the gas
-                 logger.writeln("1.2.2.1.1: gasvalve.open == true");
-                 // it is now fully open.
-                 smokeValve->fullyClose(); // so close the smokevalve, if opened
-               }
-             } else {
-               logger.writeln("1.2.2.2: tempdif >= 10");
-               gasValve.close(3); // close the gas a little bit so it won't rise to fast
-             }
-
-          } else if (tempdif < 30) { // 30 degrees to cold.
-            logger.writeln("1.2.3: tempdif < 30");
-            if (lasttempdif < 30) { // but last time it was also 30 degrees to cold
-              logger.writeln("1.2.3.1: lasttempdif < 30");
-              if (gasValve.open(5)) {// turn on the gas
-                logger.writeln("1.2.3.1.1: gasvalve.open == true");
-                // it is now fully open.
-                smokeValve->fullyClose(); // so close the smokevalve, if opened
-              }
-            } else {
-              logger.writeln("1.2.3.2: lasttempdif >= 30");
-              gasValve.close(1); // close the gas a little bit so it won't rise to fast
-            }
-
-          } else {
-            logger.writeln("1.2.4: tempdif >= 30");
-            gasValve.fullyOpen();
-            smokeValve->fullyClose();
-          }
-        }
-
-      }
-
-
-
-      // als tempdif < 0 betekent dat de max-temp overschreden is. Afhankelijk van de grootte van de overschrijding
-      // zal de gaskraan helemaal dicht moeten en de rookklep open.
-      if (tempdif < 0) {
-        logger.writeln("2: tempdif < 0");
-        if (lasttempdif < 0) { // Hij was vorige keer ook al te warm.
-          logger.writeln("2.1: lasttempdif < 0");
-          // now check the position of the gasvalve
-          if (gasValve.isFullyClosed()) { // the GasValve is already totally closed
-            logger.writeln("2.1.1: gasValve.isFullyClosed()");
-            // So check the smokeValve
-            if (smokeValve->isFullyOpen()) { // Is the smokevalve totally open?
-              logger.writeln("2.1.1.1: smokeValve->isFullyClosed()");
-              // I don't know what to do now. Gas is off, smokevalve totally open. Just wait for the temp to drop.
-            } else {
-              logger.writeln("2.1.1.2: !smokeValve->isFullyClosed()");
-              if (tempdif > -1) { // just 1 degree to hot?
-                logger.writeln("2.1.1.2.1: tempdif > -1");
-                smokeValve->open(1); // just 1 step extra open
-              } else if (tempdif >-3) {
-                logger.writeln("2.1.1.2.2: tempdif > -3");
-                smokeValve->open(5); // 5 steps extra open
-              } else { // More than 3 degrees to hot? Open the smokevalve totally
-                logger.writeln("2.1.1.2.3: tempdif <= -3");
-                smokeValve->fullyOpen();
-              }
-            }
-          } else { // the gasvalve is not fully closed, but the temp is to hot. Just close it now
-            logger.writeln("2.1.2: !gasValve.isFullyClosed()");
-            gasValve.fullyClose();
-
-            if (tempdif >-3) { // 3 degrees to hot? Open the smokevalve so the temp can drop faster
-              logger.writeln("2.1.2.1: tempdif > -3");
-              smokeValve->open(10); // 10 steps extra open
-            } else { // More than 3 degrees to hot? Open the smokevalve totally
-              logger.writeln("2.1.2.2: tempdif <= -3");
-              smokeValve->fullyOpen();
-            }
-          }
-        } else { // last time it was not to hot, so it is just to hot
-          logger.writeln("2.2: lasttempdif >= 0");
-          if (gasValve.isFullyClosed()) { // is the gasvalve already closed?
-            logger.writeln("2.2.1: gasValve.isFullyClosed()");
-            if (smokeValve->isFullyOpen()) { // is the smokevalve already open?
-              logger.writeln("2.2.1.1: smokeValve->isFullyOpen()");
-              // Don't know what to do now. Both controls are exhausted
-            } else { // only the smokeValve is usable to regulate the temperature
-              logger.writeln("2.2.1.2: !smokeValve->isFullyOpen()");
-              if (tempdif > -1) { // just 1 degree to hot?
-                logger.writeln("2.2.1.2.1: tempdif > -1");
-                smokeValve->open(1); // just 1 step extra open
-              } else if (tempdif >-3) {
-                logger.writeln("2.2.1.2.2: tempdif > -3");
-                smokeValve->open(5); // 5 steps extra open
-              } else { // More than 3 degrees to hot? Open the smokevalve totally
-                logger.writeln("2.2.1.2.3: tempdif <= -3");
-                smokeValve->fullyOpen();
-              }
-            }
-          } else { // the gasvalve is not fully closed yet.
-           logger.writeln("2.2.2: !gasValve.isFullyClosed()");
-           if (tempdif > -1) { // just 1 degree to hot?
-              logger.writeln("2.2.2.1: tempdif > -1");
-              if (gasValve.close(2)) { // close 2 steps, but is it totally closed now?
-                logger.writeln("2.2.2.1.1: gasvalve.close == true");
-                smokeValve->open(5); // Open more, because gas is closed now
-              }  else {
-                logger.writeln("2.2.2.1.2: gasvalve.close != true");
-                smokeValve->open(1); // just 1 step extra open
-              }
-            } else if (tempdif >-3) {
-              logger.writeln("2.2.2.2: tempdif > -3");
-              if (gasValve.close(5)) {
-                logger.writeln("2.2.2.2.1: gasvalve.close == true");
-                smokeValve->open(20);
-              } else {
-                logger.writeln("2.2.2.2.2: gasvalve.close != true");
-                smokeValve->open(5); // 5 steps extra open
-              }
-            } else { // More than 3 degrees to hot? Open the smokevalve totally
-              logger.writeln("2.2.2.3: tempdif <= -3");
-              gasValve.fullyClose();
-              smokeValve->fullyOpen();
-            }
-          }
-        }
-      }
-
-      // store the current temps for the next round, so we can see how fast the temp is raising or dropping
-      lasttemp = temp;
-      lasttempdif = tempdif;
-
-      // now make sure the interval is reset
-      lastregulation = RTC.get();
-      // now check if the endtime is reached
-      long seconds_smoking_left = determineSmokingTimeLeftInSeconds(starttime, lastregulation, rooktijd);
-      tft->displayTimeRemaining(seconds_smoking_left, smoking_started);
-      if (seconds_smoking_left<0) {
-        smoking_started=false;
-        firstSmokeLoop=true;
-        logger.writeln("Smoking stopped because end time is reached");
-        for (int l = 0;l<10;l++) {
-          led1.changeColor(&COLOR_BLUE);
-          speaker.on();
-          delay(500);
-          led1.changeColor(&COLOR_GREEN);
-          speaker.off();
-          delay(500);
-        } // for
-        led1.changeColor(&COLOR_GREEN);
-      } // end time reached?
-    } // regulator cycle loop
-  } // smoking started
-} // main loop
-
-/*
- * calculates the remaining time in seconds
- */
-long determineSmokingTimeLeftInSeconds(time_t starttime, time_t currenttime, int smoketime_in_minutes) {
-  long timeSmokerActiveInSeconds = currenttime - starttime;
-  long totalSmokingTimeInSeconds = (long)smoketime_in_minutes * 60l;
-
-  return totalSmokingTimeInSeconds - timeSmokerActiveInSeconds;
-}
-
-/*
- * this method writes the value to the console if the board is connected.
- */
-void debug(char* str) {
-  logger.writeln(str);
-}
-
-/*
- * This is the initialization code for the menu-class. This can be controlled by a rotary encoder and a button
- */
-void createMenu() {
-  StringOption* opt = new StringOption("Vat\0");
-  opt->addOption("Vlees\0");
-
-  StringOption* startopties = new StringOption("Nee\0");
-  startopties->addOption("Ja\0");
-
-  FloatSelector *tempsel = new FloatSelector("Stel temperatuur in:\0", &target_temp, 0.5f, 10, 250);
-  StringSelector *valuesel = new StringSelector("Meet locatie:\0", &target_temp_location, opt);
-  TimeSelector *timesel = new TimeSelector("Rooktijd:\0", &rooktijd, 5);
-  StringSelector *smokestartsel = new StringSelector("Nu starten:\0", &smoking_started, startopties);
-
-  Menu *instellingen = new Menu();
-
-  IntSelector *hoursel = new IntSelector ("Selecteer huidige uur:\0", &current_hour, 1, 0, 23);
-  IntSelector *minutesel = new IntSelector ("Selecteer huidige minuut:\0", &current_minute, 1, 0, 59);
-  instellingen->addItem(20, "Stel uren in", false, NULL, hoursel);
-  instellingen->addItem(21, "Stel minuten in", false, NULL, minutesel);
-
-  IntSelector *daysel = new IntSelector ("Selecteer huidige dag:", &current_day, 1, 1, 31);
-  IntSelector *monthsel = new IntSelector ("Selecteer huidige maand:", &current_month, 1, 1, 12);
-  IntSelector *yearsel = new IntSelector ("Selecteer huidige jaar:", &current_year, 1, 2014, 2020);
-  instellingen->addItem(22, "Stel dag in", false, NULL, daysel);
-  instellingen->addItem(23, "Stel maand in", false, NULL, monthsel);
-  instellingen->addItem(24, "Stel jaar in", false, NULL, yearsel);
-
-  mainMenu->addItem(1, "Start roken\0", false, NULL, smokestartsel);
-  mainMenu->addItem(2, "Doel temperatuur\0", false, NULL, tempsel);
-  mainMenu->addItem(3, "Vlees of vat sensor\0", false, NULL, valuesel);
-  mainMenu->addItem(4, "Rooktijd\0", false, NULL, timesel);
-  mainMenu->addItem(5, "Instellingen\0", true, instellingen, NULL);
-}
-
-/*
-The interrupt routine for the button
- */
-void bPressed() {
-  mainMenu->selectCurrent();
-  wasInSelected = true;
-};
-
-/*
-Map the pin to an interrupt number for the Arduino Mega
- */
-int getInterruptForPin (uint8_t pin) {
-  int interrupt=-1;
-
-  switch (pin) {
-  case 2:
-    interrupt=0;
-    break;
-  case 3:
-    interrupt=1;
-    break;
-  case 18:
-    interrupt=5;
-    break;
-  case 19:
-    interrupt=4;
-    break;
-  case 20:
-    interrupt=3;
-    break;
-  case 21:
-    interrupt=2;
-    break;
-  }
-  return interrupt;
-}
-
-


cleanup

cleanup

--- sensebox/sensebox.ino
+++ sensebox/sensebox.ino
@@ -38,7 +38,7 @@
 SoftwareSerial ss(2, 3);

 //Button variables
-const int buttonPin = 8;     // the number of the pushbutton pin
+const int buttonPin = 8;
 int buttonState = 0;
 int lastButtonState = 0; // variable for reading the pushbutton status
 int isOn;
@@ -177,26 +177,9 @@
       // GPS reading done
       newData = false;

-      //read sensors
-      //reading done directly due to memory limitations
-      //Serial.println("reading sensors");
-
-      //temp and humidity
-
-      //Sound
-      //loudness = analogRead(SOUND_SENSOR);
-
-      //Light
-      //brightness = TSL2561.readVisibleLux();
-
-      //Accel/Gyro
-
+      // Get Accel/Gyro data
       getAccel_Data();
       getGyro_Data();
-      //
-      //      Serial.println("Vib index:");
-      //      vib_index = abs(Axyz[0]) + abs(Axyz[1]) + abs(Axyz[2]);
-      //      Serial.println(abs(Axyz[0]) + abs(Axyz[1]) + abs(Axyz[2]));

       //Save collected data to sd card
       dataFile = SD.open("test.csv", FILE_WRITE);


Fix reading of last detailed update so that EEPROM storage of data when there is not communications happens roughly every 60 minutes (once memory is full), not every 27 minutes.

--- device.ino
+++ device.ino
@@ -252,15 +252,20 @@
 */

 bool currently_active = true;
-
+
+
+/*
+  Watchdog variables
+*/
+
+long gprs_or_wifi_watchdog_timestamp = 0;
+int  gprs_or_wifi_watchdog_counter = 0;
+#define WATCHDOG_COUNTER_MAX	12
+
 /*
   GPRS flags that describe current state of communication
 */

-long gprs_or_wifi_watchdog_timestamp = 0;
-int  gprs_or_wifi_watchdog_counter = 0;
-
-
 #define	MAX_GPRS_READ_BUFFER	64

 #ifdef WIFI_NOT_CELL
@@ -521,7 +526,7 @@
   {
     hardware_watchdog_timestamp = millis();
   }
-  else if(gprs_or_wifi_watchdog_counter < 10)
+  else if(gprs_or_wifi_watchdog_counter < WATCHDOG_COUNTER_MAX)
   {
     hardware_watchdog_timestamp = millis();
   }
@@ -900,10 +905,10 @@
       //  Need to make note of time of most recent state stored in eeprom
       //

-      last_detailed_eeprom_write  = (unsigned int) EEPROM.read(DETAILED_STATE_START_LOCATION + (detailed_state_count * DETAILED_STATE_DATA_WIDTH) + 3);
-      last_detailed_eeprom_write += (unsigned int) EEPROM.read(DETAILED_STATE_START_LOCATION + (detailed_state_count * DETAILED_STATE_DATA_WIDTH) + 2) * 256;
-      last_detailed_eeprom_write += (unsigned int) EEPROM.read(DETAILED_STATE_START_LOCATION + (detailed_state_count * DETAILED_STATE_DATA_WIDTH) + 1) * 65536;
-      last_detailed_eeprom_write += (unsigned int) EEPROM.read(DETAILED_STATE_START_LOCATION + (detailed_state_count * DETAILED_STATE_DATA_WIDTH) + 0) * 16777216;
+      last_detailed_eeprom_write  = (unsigned int) EEPROM.read(DETAILED_STATE_START_LOCATION + ((detailed_state_count - 1) * DETAILED_STATE_DATA_WIDTH) + 3);
+      last_detailed_eeprom_write += (unsigned int) EEPROM.read(DETAILED_STATE_START_LOCATION + ((detailed_state_count - 1) * DETAILED_STATE_DATA_WIDTH) + 2) * 256;
+      last_detailed_eeprom_write += (unsigned int) EEPROM.read(DETAILED_STATE_START_LOCATION + ((detailed_state_count - 1) * DETAILED_STATE_DATA_WIDTH) + 1) * 65536;
+      last_detailed_eeprom_write += (unsigned int) EEPROM.read(DETAILED_STATE_START_LOCATION + ((detailed_state_count - 1) * DETAILED_STATE_DATA_WIDTH) + 0) * 16777216;
   }

   //
@@ -1131,12 +1136,12 @@
     float closest = abs(temperature_history[BARO_HISTORY_LENGTH - 1] - average);
     temperature = temperature_history[BARO_HISTORY_LENGTH - 1];
     #ifdef BARO_DEBUG_ON
-    debug_info("Pressure " + String(BARO_HISTORY_LENGTH) + ": ", temperature_history[BARO_HISTORY_LENGTH - 1]);
+    debug_info("Temperature " + String(BARO_HISTORY_LENGTH) + ": ", temperature_history[BARO_HISTORY_LENGTH - 1]);
     #endif
     for(int_one = BARO_HISTORY_LENGTH - 2; int_one >= 0; int_one--)
     {
       #ifdef BARO_DEBUG_ON
-      debug_info("Pressure " + String(int_one) + ": ", temperature_history[int_one]);
+      debug_info("Temperature " + String(int_one) + ": ", temperature_history[int_one]);
       #endif
       if(abs(temperature_history[int_one] - average) < closest)
       {
@@ -2010,8 +2015,7 @@
 {
   latest_message_to_send = "";
   if(detailed_state_count < 1)
-  {
-    return;
+  {    return;
   }

   int which_location = DETAILED_STATE_START_LOCATION + (DETAILED_STATE_DATA_WIDTH * (detailed_state_count - 1));


Added code to test function substring_checker

--- Drones/Drones.ino
+++ Drones/Drones.ino
@@ -139,7 +139,8 @@
   }
   Serial.println();
   gpstime=substring_reader(gpsbuffer,MAX_BUFFER_SIZE,',',',');
-  if(gpstime== NULL) Serial.println("NULL");
+  //Serial.println(gpstime[0]);//Test function substring_reader
+  //if(gpstime== NULL) Serial.println("NULL");
   //Serial.println();
   array_length = 1;
   free(gpsbuffer);


reorganização do código

reorganização do código

--- EMP-B-Due.ino
+++ EMP-B-Due.ino
@@ -190,7 +190,6 @@
 void loop() {
   modoAlarme();
   standBy();
-  modoTeste();
 }

 // MODOS DE TRABALHO
@@ -267,17 +266,36 @@
 void acionaGeral() {
   btUmClique(bt_geral, &estbt_geral, &estbta_geral, &atr_geral,
              &maquina_ligada);
+  if (maquina_ligada) {
+    ligaFuncao(geral, NomeGeral);
+  } else {
+    if (ligado(geral)){
+      desligaFuncao(geral, NomeGeral);
+      resetCompleto();
+    }
+    // desligaFuncao(geral, NomeGeral);
+  }
 }

 void acionaDosador() {
   btUmClique(bt_dosador, &estbt_dosador, &estbta_dosador, &atr_dosador,
              &dosador_ligado);
+  if (dosador_ligado) {
+    ligaFuncao(dosador, NomeDosador);
+  } else {
+    desligaFuncao(dosador, NomeDosador);
+  }
 }

 void acionaDatador() {
-  if (maquina_ligada && !alarme_ativo) {
+  if (maquina_ligada) {
     btUmClique(bt_datador, &estbt_datador, &estbta_datador, &atr_datador,
                &datador_ligado);
+  }
+  if (datador_ligado) {
+    ligaFuncao(led_datador, NomeDatador);
+  } else {
+    desligaFuncao(led_datador, NomeDatador);
   }
 }

@@ -345,7 +363,7 @@
   unsigned long ativo = *inicio + map(analogRead(pot), 0, 1023, 0, ciclo_PWM);
   unsigned long inativo = ciclo_PWM - ativo;
   unsigned long pwm = *inicio + ciclo_PWM;
-  if (maquina_ligada && !alarme_ativo) {
+  if (maquina_ligada) {
     if (tempo_atual > *inicio && tempo_atual <= ativo) {
       liga(saida);
     } else if (tempo_atual > ativo && tempo_atual < pwm) {
@@ -534,24 +552,3 @@
   desliga(solda_horizontal_PWM);
   desliga(solda_datador_PWM);
 }
-
-void modoTeste() {
-  if (maquina_ligada) {
-    ligaFuncao(geral, NomeGeral);
-  } else {
-    if (ligado(geral)){
-      resetCompleto();
-    }
-    desligaFuncao(geral, NomeGeral);
-  }
-  if (dosador_ligado) {
-    ligaFuncao(dosador, NomeDosador);
-  } else {
-    desligaFuncao(dosador, NomeDosador);
-  }
-  if (datador_ligado) {
-    ligaFuncao(led_datador, NomeDatador);
-  } else {
-    desligaFuncao(led_datador, NomeDatador);
-  }
-}


Tune calculation

Tune calculation


Try to define the SUCCESS_RESPONSE and LENGTH above here.

--- SimpleCSV.ino
+++ SimpleCSV.ino
@@ -21,7 +21,8 @@
 #define FILE_HEADER              F("Content-Disposition: form-data; name=\"file\"; filename=\"f.csv\"\r\nContent-Type: text/csv\r\n\r\n")
 #define FILE_HEADER_SIZE         89 //       '         '         '          '          '          '            '         '            9

-#define SUCCESS_RESPONSE_SIZE    17
+#define SUCCESS_RESPONSE         "HTTP/1.1 200 OK\r\n"
+#define SUCCESS_RESPONSE_SIZE    16

 void initSD() {
   pinMode(SD_CHIP_SELECT_PIN, OUTPUT);
@@ -144,8 +145,9 @@
       // read to the first white space
       while (www.available()) {
         char c = www.read();
-        if (i <= 15) {
-          if (c != "HTTP/1.1 200 OK\r\n"[i++]) {
+        if (i < SUCCESS_RESPONSE_SIZE) {
+          Serial.print(SUCCESS_RESPONSE[i]);
+          if (c != SUCCESS_RESPONSE[i++]) {
             Serial.print(FAIL_MSG);
             www.close();
             return 1;


bug in startMiils.

bug in startMiils.

--- _64-esp8266-atmega328p-i2c8x8-mma-8452-dash-button/a-02-atmega328p/a-02-atmega328p.ino
+++ _64-esp8266-atmega328p-i2c8x8-mma-8452-dash-button/a-02-atmega328p/a-02-atmega328p.ino
@@ -48,7 +48,7 @@
   return sizeof (value);
 }

-unsigned int startMiils;
+unsigned long startMiils;
 uint16_t pir_interuptCount = 0;
 volatile bool haveData = false;
 volatile bool bbutton_up_isr = false;
@@ -130,6 +130,7 @@
   else
   {
     Serial.print("Wake up, startMiils : ");
+    Serial.println(startMiils);
   }
 }


Add powersave code

Add powersave code

--- esp8266_dht11_oled.ino
+++ esp8266_dht11_oled.ino
@@ -30,6 +30,13 @@
 String postData = String("temperature=");

 HTTPClient http;
+
+unsigned long lastButtonPressed = 0;
+bool displayOn = true;
+static unsigned int const PAUSE_POWERSAVE_IN_MS = 1000 * 120; //2 minutes
+static unsigned int const PAUSE_ACTIVE_IN_MS = 500; // half a sec
+static unsigned int const POWERSAVE_IN_MS = 20 * 1000; // 20 secs
+static unsigned int pause_in_ms = PAUSE_ACTIVE_IN_MS;

 static const unsigned int NUM_WIFI_FRAMES = 5;
 static const uint8_t WIFI_FRAMES[NUM_WIFI_FRAMES][32] = {
@@ -81,9 +88,6 @@
 		else
 		{
 			localIP = WiFi.localIP().toString();
-			long rssi = WiFi.RSSI();
-			Serial.print("RSSI:");
-			Serial.println(rssi);
 		}
 	}

@@ -135,13 +139,20 @@
 	wifiConnection.checkWiFi();
 }

+extern "C" void esp_schedule();
+
+extern void delay_end(void* arg);
+
 void button_pressed() {
-	Serial.println("Button pressed!");
-}
-
-void loop() {
-	wifiConnection.checkWiFi();
-
+	DEBUG_PRINTLN("Button pressed!");
+	lastButtonPressed = 0;
+	displayOn = true;
+	pause_in_ms = PAUSE_ACTIVE_IN_MS;
+	u8g2.display();
+	esp_schedule();
+}
+
+void display() {
 	String displayData;
 	sensors_event_t event;
 	dht.temperature().getEvent(&event);
@@ -183,6 +194,16 @@
 		wifiFrame = wifiFrame + 1 % NUM_WIFI_FRAMES;
 	u8g2.drawXBM(SCREEN_WIDTH - 16, SCREEN_HEIGHT - 16, 16, 16, WIFI_FRAMES[wifiFrame]);
 	u8g2.sendBuffer();
+
+}
+
+void loop() {
+	wifiConnection.checkWiFi();
+
+	if (displayOn) {
+		display();
+	}
+

 	/*
 	  http.begin("http:///");
@@ -205,7 +226,16 @@

 	  http.end();
 	*/
-	delay(1000 * 1);
-}
-
-
+	lastButtonPressed += pause_in_ms; // a little false since we are doing other, stuff, but, meh
+	DEBUG_PRINTLN(lastButtonPressed);
+	if (lastButtonPressed > POWERSAVE_IN_MS)
+	{
+		pause_in_ms = PAUSE_POWERSAVE_IN_MS;
+		displayOn = false;
+		u8g2.noDisplay();
+	}
+
+	delay(pause_in_ms);
+}
+
+