Count Time in 2 different states

I'm trying to create a simple Game.
The idea is to count in millis

  1. how fast the player reacts(Releases a switch when a RedLight turns ON
    2)how fast he can solve the puzzle (when puzzle solved he pussh a different Switch)
    Following PaulS advice...i rebuilded the code made here Game Reaction tester and two capacitive sensors - Programming Questions - Arduino Forum to the following
#include <CapacitiveSensor.h>

const int RedLight         =  6;    // red stop LED
const int BlueLight         =  10;    // red stop LED
const int StartSwitch      =  13;    // reaction timer button
int StartState = 0;         // variable for reading the pushbutton status

int BaseState = 0;           //this variable controls if BaseSensor is ON=1 or OFF=0
CapacitiveSensor   BaseSensor = CapacitiveSensor(7,8);        // 10 megohm resistor between pins 4 & 2, pin 2 is sensor pin, add wire, foil
int EndState = 0;           //this variable controls if EndSensor is ON=1 or OFF=0
CapacitiveSensor   EndSensor = CapacitiveSensor(7,9);        // 10 megohm resistor between pins 4 & 2, pin 2 is sensor pin, add wire, foil
long randomDelayTime;   
long timerStartMillis;       // the time when the timer started
long timerMidMillis;         // the time when in Mid state
long timerEndMillis;         // the time when the timer finished
long difference2;
long difference;
boolean PrepareState = true; // in introduction mode

void setup() {
  
 
  pinMode(RedLight, OUTPUT);       // red LED is an output
  pinMode(BlueLight, OUTPUT);       // Blue LED is an output
  pinMode(StartSwitch, INPUT);     // button is an input
  
   BaseSensor.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
   EndSensor.set_CS_AutocaL_Millis(0xFFFFFFFF);
   long start = millis();
   long total1 =  BaseSensor.capacitiveSensor(10);
   long total2 =  EndSensor.capacitiveSensor(10);
  
   pinMode(StartSwitch, INPUT);     // button is an input 
  
   randomSeed(analogRead(2));     // use unconnected pin to seed random sequence
   Serial.begin(9600);
}



void loop() 
{
    StartState = digitalRead(StartSwitch);
    long start = millis();
    long total1 =  BaseSensor.capacitiveSensor(10);
    long total2 =  EndSensor.capacitiveSensor(10);
    
        
    if (total1 > 20){ BaseState =1; } else { BaseState =0; }
     
    if (total2 > 20){ EndState =1; } else { EndState =0; }
  
  
  if(PrepareState) // Prepare State
  {
    digitalWrite(BlueLight, HIGH); // PREPARE STATE = BLUE LIGHT ON
    
    if(BaseState == 1) // ===================================================== TEST BASE LIGHT
    {
      Serial.println(" Prapare State and  Base Pressed  ");
      digitalWrite(RedLight, HIGH);
    }
    else
    {
     Serial.println("  Prepare  "); 
     digitalWrite(RedLight, LOW);
    } 
    if(EndState == 1) // =======================================================  TEST END LIGHT
    {
      Serial.println(" Prapare State and  END Pressed  ");
      digitalWrite(RedLight, HIGH);
    }
    else
    {
     Serial.println("  Prepare  "); 
     digitalWrite(RedLight, LOW);
    } 
    
    if(BaseState ==1 && StartState == 1)// StartState Pressed Prepare State OFF
    {
       Serial.println(" Prepare State and Start State Pressed  "); 
       digitalWrite(BlueLight, LOW); // NO PREPARE STATE = BLUE LIGHT ON
       digitalWrite(RedLight, LOW);
       //randomDelayTime = random(10000);  // this is the random amount to be used 0-10 seconds
       //delay(randomDelayTime);
       delay(2000);
       timerStartMillis = millis(); // get the current time 
       PrepareState=false ;
    }
      
  }
  else //No Prepare State
  { 
      Serial.print(" TIMER START ");
      Serial.println(timerStartMillis);
      digitalWrite(RedLight,HIGH);
      
      if (BaseState==0) // ===============================================================   Base Released
      {
        timerMidMillis = millis(); // get the current time
        difference = timerMidMillis - timerStartMillis; // time taken is difference between times
        Serial.print(" TIMER MID ");
        Serial.println(timerMidMillis);
                  
        while(EndState == 1) // =============================================  End Pressed Prepare State ON
        {     
            timerEndMillis = millis(); // get the current time   
            difference2 = timerEndMillis - timerMidMillis; // time taken is difference between times
            Serial.print(" TIMER END ");
            Serial.println(timerEndMillis);
            digitalWrite(RedLight,LOW); 
            
        }        
          //  Serial.print("  difference  ");
          //  Serial.print(difference); 
         //   Serial.print("  difference2  ");
          //  Serial.println(difference2); 
          
          if (StartState==1)
          {
             PrepareState = true;
          }
      }
  } // No Prepare State
}

The problem is at the last stages of the code..
Take a look at the values i'm taking in serial

TIMER START 4574   <<<<<---------------------timerStartMillis = millis();
 TIMER START 4574
 TIMER START 4574
 TIMER START 4574
 TIMER START 4574
 TIMER START 4574
 TIMER MID 4803
 TIMER START 4574
 TIMER MID 4841 <<---------------------When BaseState ==0 (Switch released)
 TIMER START 4574
 TIMER START 4574
 TIMER MID 4897
 TIMER START 4574
 TIMER MID 4935
 TIMER START 4574
 TIMER MID 4973
 TIMER START 4574
 TIMER MID 5010
 TIMER START 4574
 TIMER MID 5048
 TIMER START 4574
 TIMER MID 5085
 TIMER END 5103 << -----------------------------When EndState ==1 (End switch pressed)
 TIMER END 5121
 TIMER END 5138
 TIMER END 5155
 TIMER END 5174
 TIMER END 5191
 TIMER END 5209
 TIMER END 5226
 TIMER END 5244
 TIMER END 5262
 TIMER END 5279
 TIMER END 5297
 TIMER END 5315
 TIMER END 5332
 TIMER END 5350
 TIMER END 5368
 TIMER END 5386
 TIMER END 5403
 TIMER END 5421

although i'm taking the desired values the loop continues for ever so i cant calculate the differences i want to count

  Serial.print("  difference  ");
  Serial.print(difference); 
  Serial.print("  difference2  ");
  Serial.println(difference2);

So my questions are :

  1. What did i have to do in order to display the two values difference and difference2 stable?
  2. Is it possible when all values displayed correctly when i StartState==1 to start over the Game ?

PS1. Later , I'm planning to use an LCD screen in order to display results

PS2. I'm struggling several days on this...with no luck .. :blush:

Thank you in advance.

I think you need to re-write your code from scratch. Think about what should happen on each pass through loop. If the start switch has not been pressed, is there any reason to read the two capacitive sensors? If the start switch has been pressed, is there any reason to read it again?

You need a state machine. You have only a few states - not yet started, started, timing, reacted, and done. That is, the user has not yet started the process, the user has started the process (so LED is off and the random delay is happening), the LED is on and timing has begun, and, the user has reacted to the LED coming on. Certain state changes happen because the user did something. Some happen at specific times (relative to other events).

In some states, you need to do something. In others, you are simply testing whether the user has done something.

In the reacted state, you calculate how long is took for the user to react, and you transition to the done state. In the done state, you display the results,.

Thank you Paul for your valuable help..
without your help i could not make any progress ....
especially thank you for pointing me the right way i should think and work

PaulS:
I think you need to re-write your code from scratch.

Done

PaulS:
If the start switch has not been pressed, is there any reason to read the two capacitive sensors?

Yes there is.
I need to test the sensors and to adjust the threshold with a pot individually for each sensor (to be done)

PaulS:
If the start switch has been pressed, is there any reason to read it again?

Yes

PaulS:
You need a state machine. You have only a few states - not yet started, started, timing, reacted, and done. That is, the user has not yet started the process, the user has started the process (so LED is off and the random delay is happening), the LED is on and timing has begun, and, the user has reacted to the LED coming on. Certain state changes happen because the user did something. Some happen at specific times (relative to other events)

In the reacted state, you calculate how long is took for the user to react, and you transition to the done state. In the done state, you display the results,.

I guess that the new code complying with all the above...
Right ?

Here is the NEWly written code that is working.....i guess :blush:

#include <CapacitiveSensor.h>

const int RedLight         =  6;    // red stop LED
const int BlueLight         =  10;    // red stop LED
const int StartSwitch      =  13;    // reaction timer button
int StartState = 0;         // variable for reading the pushbutton status

int BaseState = 0;           //this variable controls if BaseSensor is ON=1 or OFF=0
CapacitiveSensor   BaseSensor = CapacitiveSensor(7,8);        // 10 megohm resistor between pins 4 & 2, pin 2 is sensor pin, add wire, foil
int EndState = 0;           //this variable controls if EndSensor is ON=1 or OFF=0
CapacitiveSensor   EndSensor = CapacitiveSensor(7,9);        // 10 megohm resistor between pins 4 & 2, pin 2 is sensor pin, add wire, foil
long randomDelayTime;   
long timerStartMillis;       // the time when the timer started
long timerMidMillis;         // the time when in Mid state
long timerEndMillis;         // the time when the timer finished
long difference2;
long difference;
boolean PrepareState = true; // in introduction mode

boolean GameStart = false;
boolean GameMid = false;
boolean GameEnd = false;

void setup() {
  
 
  pinMode(RedLight, OUTPUT);       // red LED is an output
  pinMode(BlueLight, OUTPUT);       // Blue LED is an output
  pinMode(StartSwitch, INPUT);     // button is an input
  
   BaseSensor.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
   EndSensor.set_CS_AutocaL_Millis(0xFFFFFFFF);
   long start = millis();
   long total1 =  BaseSensor.capacitiveSensor(10);
   long total2 =  EndSensor.capacitiveSensor(10);
  
   pinMode(StartSwitch, INPUT);     // button is an input 
  
   randomSeed(analogRead(2));     // use unconnected pin to seed random sequence
   Serial.begin(9600);
}



void loop() 
{
    StartState = digitalRead(StartSwitch);
    long start = millis();
    
    long total1 =  BaseSensor.capacitiveSensor(10);
    if (total1 > 20){ BaseState =1; } else { BaseState =0; }
    
    long total2 =  EndSensor.capacitiveSensor(10);
    if (total2 > 20){ EndState =1; } else { EndState =0; }
  
  
  if(PrepareState) // Prepare State
  {
    digitalWrite(BlueLight, HIGH); // PREPARE STATE = BLUE LIGHT ON
    
    if(BaseState == 1) // ===================================================== TEST BASE LIGHT
    {
      Serial.println(" Prapare State and  Base Pressed  ");
      digitalWrite(RedLight, HIGH);
    }
    else
    {
     Serial.println("  Prepare  "); 
     digitalWrite(RedLight, LOW);
    } 
    if(EndState == 1) // =======================================================  TEST END LIGHT
    {
      Serial.println(" Prapare State and  END Pressed  ");
      digitalWrite(RedLight, HIGH);
    }
    else
    {
     Serial.println("  Prepare  "); 
     digitalWrite(RedLight, LOW);
    } 
    
    if(BaseState ==1 && StartState == 1)// StartState Pressed Prepare State OFF
    {
       //Serial.println(" Prepare State and Start State Pressed  "); 
       digitalWrite(BlueLight, LOW); // NO PREPARE STATE = BLUE LIGHT ON
       digitalWrite(RedLight, LOW);
       //randomDelayTime = random(10000);  // this is the random amount to be used 0-10 seconds
       //delay(randomDelayTime);
       delay(2000);
       timerStartMillis = millis(); // get the current time             
       PrepareState=false ;
       GameStart=true;
    }
      
  }
  else //No Prepare State
  { 
                 
       if(GameStart == true) /// Lets Start count TIMES
       {
                
          if (BaseState == 1) // ===============================================================   Base Released
          {
            
            digitalWrite(RedLight,HIGH);
            Serial.print("  TimerStarts ");
            Serial.println(timerStartMillis);
            
          }
         else
        {
            timerMidMillis = millis(); // get the current time
            difference = timerMidMillis - timerStartMillis; // time taken is difference between times
            Serial.print("  difference  ");
            Serial.println(difference);
            GameStart=false;
            GameMid=true;
        } 
       } 
      
       if (GameStart == false && GameMid == true)
       { 
         if(EndState == 1) // =============================================  End Pressed Prepare State ON
          {     
             timerEndMillis = millis(); // get the current time   
             difference2 = timerEndMillis - timerMidMillis; // time taken is difference between times
             digitalWrite(RedLight,LOW); 
             GameMid=false;
             GameEnd=true;
          }        
       }     
       
       if (GameStart == false && GameMid == false && GameEnd == true)
       {
            if (StartState==1) // Start Pressed...Lets Start Over
             {
                 PrepareState = true;
                 GameStart=false;
                 GameMid=false;
                 GameEnd=false;
             }
            else
            {
                Serial.print("  difference  ");
                Serial.print(difference); 
                Serial.print("  difference2  ");
                Serial.println(difference2); 
             
            }
         }
  }      
}

The questions now are:
**1)**The way that i've structure my code is it counting correctly the differences of each state ?
**2)**There is any way to calculate the latency introduced by the Capacitive Sensors ?

Yes there is.
I need to test the sensors and to adjust the threshold with a pot individually for each sensor (to be done)

No. That should not be done on every pass through loop. That should be done in a calibrate() routine that rarely gets called.

Yes

Why?

1)The way that i've structure my code is it counting correctly the differences of each state ?

I don't know. There is still too much stuff happening on each pass trough loop.

    StartState = digitalRead(StartSwitch);
    long start = millis();
    
    long total1 =  BaseSensor.capacitiveSensor(10);
    if (total1 > 20){ BaseState =1; } else { BaseState =0; }
    
    long total2 =  EndSensor.capacitiveSensor(10);
    if (total2 > 20){ EndState =1; } else { EndState =0; }

You have not implemented a state machine. A state machine would look something like this:

int state = 0; // state will be 0 = idle; 1 = started; 2 = keeping user guessing; 3 = timing; 4 = reacted; 5 = done
void loop()
{
   switch(state)
   {
   }
}

In the switch statement, you'd have cases for each state (and there may need to be more (or less) states. For instance, you might have:

   case 0: // idle
      if(digitalRead(StartSwitch) == HIGH)
      {
         // User wants to start
         // Pick a random time until the LED should be turned on
         state = 1; // Move to the next state
      }
      break;

You might have:

   case 2: // Keeping user guessing
      if(millis() - startTime >= randomInteral)
      {
          // Turn LED on
          reactionStart = millis();
          state = 3; // move to timing state
      }
      break;

Perhaps you'd have:

    case 3:
       // Read 2nd capacitive sensor
       if(sensorValue > pressedThresholdTwo)
       {
          reactionEnd = millis(); // Note when this happened
          state = 4;
       }
       break;

Not much happens in state 4. You simply calculate the reaction time, and change to state 5.

Most of the time will probably be spent in state 5, where you display the reaction time on the LCD (and test the start switch state to determine when to change to state 0 again).

You may need to add, or remove state, and renumber accordingly.

Now, I'm not clear on why there is a start switch and two capacitive sensors. Is the user is supposed to press the start switch to start the game (re)running, and then press the first start capacitive sensor to trigger the random delay time? Does timing start when the LED is turned on, and stop when it is turned off (because the use pressed the second capacitive sensor)? If so, why are there two intervals being measured? I see the need to measure only one - from when the LED comes on until the second capacitive sensor is pressed.

In a situation like this, I find it helpful to write the user manual first. Explain exactly what the user is supposed to do, in the order that the user is expected to do things.

PaulS:
In a situation like this, I find it helpful to write the user manual first. Explain exactly what the user is supposed to do, in the order that the user is expected to do things.

I'll start from this.

USER MANUAL. XD

  1. The referee calibrates the system (sensitivity of sensors using pots)
    2)The player put his hand over the 1st capacitive sensor ( he is ready to play )
  2. The referee hit the start button (game begin)
  3. After a random amount of time a RedLight goes ON (At this point 1st Timing begin)
  4. Player remove his hand over the 1st capacitive sensor and starts solving the puzzle(here we stop 1st counting to measure how fast the player reacted AND also starting the 2nd counting)
  5. Player put his hand oner the 2nd Capacitive sensor when puzzle solved(Here we stop 2nd counting to measure in how much time the player solved the puzzle )
    7)Display the results
    8 ) Referee hits the start button and GAME starts again

PaulS:
You may need to add, or remove state, and renumber accordingly.

Take a look on what i've done

#include <CapacitiveSensor.h>

const int RedLight         =  6;    // red stop LED
const int BlueLight         =  10;    // red stop LED
const int StartSwitch      =  13;    // reaction timer button

const int PotBase = A0;       // analog IN Sensitinity Base
int PotBaseVal = 0;           // variable to store the value read from PotBase A3
int BaseSense = 0;            // value to adjust Base sensitivity
int BaseState = 0;           //this variable controls if BaseSensor is ON=1 or OFF=0

CapacitiveSensor   BaseSensor = CapacitiveSensor(7,8);        // 10 megohm resistor between pins 4 & 2, pin 2 is sensor pin, add wire, foil

const int PotEnd = A1;       // analog IN Sensitinity End
int PotEndVal = 0;           // variable to store the value read from PotEnd A1
int EndSense = 0;            // value to adjust End sensitivity
int EndState = 0;           //this variable controls if EndSensor is ON=1 or OFF=0
CapacitiveSensor   EndSensor = CapacitiveSensor(7,9);        // 10 megohm resistor between pins 4 & 2, pin 2 is sensor pin, add wire, foil

int GameState = 0; // state will be 0 = idle; 1 = started; 2 = keeping user guessing; 3 = timing; 4 = reacted; 5 = done
long timerStartMillis;       // the time when the timer started
long timerMidMillis;         // the time when in Mid state
long timerEndMillis;         // the time when the timer finished
long difference2;
long difference;

void setup() 
{
  pinMode(RedLight, OUTPUT);       // red LED is an output
  pinMode(BlueLight, OUTPUT);       // Blue LED is an output
  pinMode(StartSwitch, INPUT);     // button is an input
  
//  BaseSensor.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
//  EndSensor.set_CS_AutocaL_Millis(0xFFFFFFFF);
  long start = millis();
//  long total1 =  BaseSensor.capacitiveSensor(10);
//  long total2 =  EndSensor.capacitiveSensor(10);
     
  randomSeed(analogRead(2));     // use unconnected pin to seed random sequence
  Serial.begin(9600);
}

  

void loop()
{
  BaseState = ReadBaseSensor(); 
  EndState  = ReadEndSensor();
  
   switch(GameState)
   {
      
      case 0: //  CALIBRATE....This will run OLNLY at STARTUP
      
          if(digitalRead(StartSwitch) == HIGH) // Start Switch Pressed and GAME BEGINS !!!
          {  
             delay(2000);
             digitalWrite(BlueLight,LOW);
             digitalWrite(RedLight,HIGH);
             timerStartMillis = millis();           
             GameState = 1; // Move to the next state
          }
          else
          {
             Serial.println("  CALIBRATE  "); 
             digitalWrite(BlueLight,HIGH); 
          }
          
      break;
      
      case 1: 
              
          if(BaseState == 1)
          {
             Serial.println("  BASE PRESSED  ");             
             
          }
          else
          {
            
            Serial.println("  BASE RELEASED  "); 
            timerMidMillis = millis(); // get the current time
            difference = timerMidMillis - timerStartMillis; // time taken is difference between times
            Serial.print("  difference  ");
            Serial.println(difference);
            GameState = 2; // Move to the next state 
          }
          
        break;
        
        case 2: // idle CALIBRATE
        
          if(EndState == 1)
          {
             Serial.println("  END PRESSED  ");  
             timerEndMillis = millis(); // get the current time   
             difference2 = timerEndMillis - timerMidMillis; // time taken is difference between times
             digitalWrite(RedLight,LOW);
             GameState = 3; // Move to the next state           
             
          }
          else
          {
            Serial.println("  END RELEASED  "); 
          }
          
         break;
          
         case 3: // DISPLAY RESULTS
         
          if(digitalRead(StartSwitch) == HIGH)
          {
             GameState = 1; // Move to case 1
          }
          else
          {
             Serial.println("  DISPLAY RESULTS  "); 
             Serial.print("  difference  ");
             Serial.print(difference); 
             Serial.print("  difference2  ");
             Serial.println(difference2);  
          }
          
         break;
   }
}

int ReadBaseSensor(){
  BaseSensor.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
  long total1 =  BaseSensor.capacitiveSensor(10);
  if (total1 > 20) { return 1; } else { return 0; }
}

int ReadEndSensor(){
  EndSensor.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
  long total2 =  EndSensor.capacitiveSensor(10);
  if (total2 > 20) { return 1; } else { return 0;}
}

I tryied to avoid running all this in every loop

    StartState = digitalRead(StartSwitch);
    long start = millis();
    
    long total1 =  BaseSensor.capacitiveSensor(10);
    if (total1 > 20){ BaseState =1; } else { BaseState =0; }
    
    long total2 =  EndSensor.capacitiveSensor(10);
    if (total2 > 20){ EndState =1; } else { EndState =0; }

so i created two functions to read the sensors individually
ReadBaseSensor() and ReadEndSensor()

but i place them in the beginning of the loop in order to work ...which means that will running in every loop...right ?
I tried to put them inside the switch statement to avoid the above but is not working

case 1: 
          BaseState = ReadBaseSensor();  /// <<<<<<--------------Here NOT WORKING -------------    
          if(BaseState == 1)
          {
             Serial.println("  BASE PRESSED  ");             
             
          }
          else
          {
            Serial.println("  BASE RELEASED  "); 
            GameState = 2; // Move to the next state 
          }
          
        break;

How can i avoid running this parts of code in every loop ?

So, you are trying to measure reaction time (how long between when the LED goes on and when the reactee contacts the capacitive sensor.

Then, you are measuring how long it takes the user to solve some undefined puzzle and press the second capacitive sensor.

The bit about solving a puzzle is completely new information and is EXACTLY why I suggested that you needed to write the user guide first.

void loop()
{
  BaseState = ReadBaseSensor(); 
  EndState  = ReadEndSensor();

No. Unless the LED is lit, there is no reason to read the base sensor. The LED won't be lit until the referee has pressed the start switch. Unless the base sensor has been contacted, and the user is solving the puzzle, there is no need to read the end sensor.

      case 0: //  CALIBRATE....This will run OLNLY at STARTUP
      
          if(digitalRead(StartSwitch) == HIGH) // Start Switch Pressed and GAME BEGINS !!!
          {  
             delay(2000);
             digitalWrite(BlueLight,LOW);
             digitalWrite(RedLight,HIGH);
             timerStartMillis = millis();           
             GameState = 1; // Move to the next state
          }
          else
          {
             Serial.println("  CALIBRATE  "); 
             digitalWrite(BlueLight,HIGH); 
          }
          
      break;

I don't see how anything that is happening here is even vaguely related to calibrating anything.

            Serial.println("  BASE RELEASED  "); 
            timerMidMillis = millis(); // get the current time

So, timerMidMillis - timerStartMillis will include the time it took to serial print that message. Is that reasonable?

        case 2: // idle CALIBRATE
        
          if(EndState == 1)
          {
             Serial.println("  END PRESSED  ");  
             timerEndMillis = millis(); // get the current time   
             difference2 = timerEndMillis - timerMidMillis; // time taken is difference between times
             digitalWrite(RedLight,LOW);
             GameState = 3; // Move to the next state           
             
          }
          else
          {
            Serial.println("  END RELEASED  "); 
          }
          
         break;

Again, I see nothing even vaguely related to calibration. Unless you mean something completely different than "calibrate" normally means.

Other than that, I think you are now on the right track.

PaulS:
So, you are trying to measure reaction time (how long between when the LED goes on and when the reactee contacts the capacitive sensor.

Then, you are measuring how long it takes the user to solve some undefined puzzle and press the second capacitive sensor.

The bit about solving a puzzle is completely new information and is EXACTLY why I suggested that you needed to write the user guide first.

void loop()

{
  BaseState = ReadBaseSensor();
  EndState  = ReadEndSensor();



No. Unless the LED is lit, there is no reason to read the base sensor. The LED won't be lit until the referee has pressed the start switch. Unless the base sensor has been contacted, and the user is solving the puzzle, there is no need to read the end sensor.

i know...
tried to avoid that but when i put this part of the code inside the case 1 (look in the code below) right before the... if(BaseState == 1) ... doesn't work :blush:
What i'm doing wrong ?

 case 1: 
          
          BaseState = ReadBaseSensor();  <<------here----
          if(BaseState == 1)
          {
             Serial.println("  BASE PRESSED  ");             
             
          }
..........etc.....

PaulS:
Other than that, I think you are now on the right track.

:slight_smile: Thank you

i know...
tried to avoid that but when i put this part of the code inside the case 1 (look in the code below) right before the... if(BaseState == 1) ... doesn't work smiley-red
What i'm doing wrong ?

Failing to define what "doesn't work" means.

Does the code fail to compile? Is the function not called? Does it return incorrect results? I the return value not persisted correctly?

PaulS:
Failing to define what "doesn't work" means.

Does the code fail to compile? Is the function not called? Does it return incorrect results? I the return value not persisted correctly?

Compiles correctly.
When i place the BaseState = ReadBaseSensor(); at the beginning of the loop and BaseSensor is pressed

void loop()
{
       BaseState = ReadBaseSensor(); 
       EndState  = ReadEndSensor();

the code working as expected and i'm taking the following readings in Serial

  CALIBRATE  
------------  BaseState ---------------1
  BASE PRESSED  
------------  BaseState ---------------0
  BASE RELEASED

But when i place it inside the case1

case 1: 
          
          BaseState = ReadBaseSensor(); 
          Serial.print("------------  BaseState ---------------"); 
          Serial.println(BaseState); 
          if(BaseState == 1)
         {
        ..........................etc ....................

in Serial i'm getting

 CALIBRATE  
------------  BaseState ---------------0
  BASE RELEASE

and the code doesnt run as expected.

I guess that this mean that the function is not called or returns wrong results.

I guess that this mean that the function is not called or returns wrong results.

You could verify that the function is, or is not called, by putting a Serial.print() statement in the function.

You could verify that the function returns the correct, or wrong, results, by setting BaseState to some value that the function would not possibly return. If it retains that value after the function call, you have one problem. If it changes, you have another problem.

PaulS:

I guess that this mean that the function is not called or returns wrong results.

You could verify that the function is, or is not called, by putting a Serial.print() statement in the function.

Done.
Tested and the function called .

PaulS:
You could verify that the function returns the correct, or wrong, results, by setting BaseState to some value that the function would not possibly return. If it retains that value after the function call, you have one problem. If it changes, you have another problem.

The function returns wrong results.
I've set BaseState=2; and the function always return zero

I'm trying to help you debug your code, but you're really not making it easy.

The function used to look like this:

int ReadBaseSensor(){
  BaseSensor.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
  long total1 =  BaseSensor.capacitiveSensor(10);
  if (total1 > 20) { return 1; } else { return 0; }
}

Done.
Tested and the function called .

So, you made some changes.

The function returns wrong results.
I've set BaseState=2; and the function always return zero

What value are you reading from the sensor?

Feel free to volunteer information that you think might be useful.

PaulS:
I'm trying to help you debug your code, but you're really not making it easy.

Sorry...i'm doing the best i can do :blush: :blush: :blush:

PaulS:
The function used to look like this:

int ReadBaseSensor(){

BaseSensor.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
  long total1 =  BaseSensor.capacitiveSensor(10);
  if (total1 > 20) { return 1; } else { return 0; }
}






> Done.
> Tested and the function called .


So, you made some changes.

Yes ..the new function i use in order to make sure if is called or not is the following

int ReadBaseSensor(){
  BaseSensor.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
  long total1 =  BaseSensor.capacitiveSensor(10);
  if (total1 > 20) 
  {
    Serial.print("------------  BaseState ------  1  ---------"); 
    return 1; 
  } 
  else 
  {
    Serial.print("------------  BaseState -----  0  ----------"); 
    return 0; 
  }
}

PaulS:
Feel free to volunteer information that you think might be useful.

Hmmmm...
i've made some changes and seems that when i put

BaseSensor.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
 long total1 =  BaseSensor.capacitiveSensor(10);

in void setup()
and changes function to

int ReadBaseSensor(){
  long total1 =  BaseSensor.capacitiveSensor(10);
  if (total1 > 20) 
  {
    Serial.print("------------  BaseState ------  1  ---------"); 
    return 1; 
  } 
  else 
  {
    Serial.print("------------  BaseState -----  0  ----------"); 
    return 0; 
  }
}

the function is working fine at the begining of the loopp ABD inside the case 1. :~
Any idea WHY ?

Any idea WHY ?

Nope. I've never used capacitive sensors, nor had any desire to do so.

PaulS:

Any idea WHY ?

Nope. I've never used capacitive sensors, nor had any desire to do so.

:slight_smile:

And one last question..
do you think that this aproach to calculate the latency introduced by the sensor is correct ?

case 1: 
          
          SensorStartMillis = millis();
          BaseState = ReadBaseSensor(); 
          SensorEndMillis = millis();
          SensorLatency = SensorEndMillis - SensorStartMillis; 
          Serial.print(" BASE SENSOR LATENCY  "); 
          Serial.println(SensorLatency);

do you think that this aproach to calculate the latency introduced by the sensor is correct ?

Yes.