Changing loops using ky-40 encoder button

Hi All. I am working on an electronic lead screw for my lathe driven by a closed loop stepper.
For cutting threads I need to be able to first set the pitch of the tread in mm or TPI ( threads per inch ) . Currently I have a ky-40 encoder to set the numeric value of the thread and use the button to change between MM & TPI. This numeric value from the screen is set in a float and will then used for the stepper motor control. At present the code is focused on the input select, and once I get that right, I will move on

A typical metric thread would be 1.25mm and a typical imperial thread would be 20TPI. These are fine threads

It currently works ( basically ) but does not function as I thought it would.

When I first start I get "select" on the screen I have press the button, advance it 1 click then press the button again and get 1 TPI which increments when the encoder is turned.

for mm , from start I get "select" I increment the encoder by 1, then press button and get 0.01mm

If I want to switch between the 2 I need to decrease the count until select appears, then double click, advance 1 click and it will change.

What I want to happen is that I just want to press the switch once to change between modes.
I have tried different methods using interrupts etc, but none seem to work ( I am using a Teensy 4.0, but the code is exactly the same

    #include <RotaryEncoder.h>  //Rotary_Encoder_KY-040_Fixed-main/RotaryEncoder.h https://github.com/ownprox/Rotary_Encoder_KY-040_Fixed.....NOTE. this installs as RotaryEncoder.h, so make sure to remove any existing library
    #include <Bounce.h>
    #include <SPI.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>
    #include <Fonts/FreeSansBold12pt7b.h>
    #define SCREEN_WIDTH 128     // OLED display width, in pixels 
    #define SCREEN_HEIGHT 32     // OLED display height, in pixels
    #define OLED_RESET -1        // Reset pin # (or -1 if sharing Arduino reset pin)
    #define SCREEN_ADDRESS 0x3C  ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
    #define BUTTON 6 // was pin 6
   
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

    int Counter = 0, LastCount = 0; //uneeded just for test
    float Pitchmm ; // used for metric leadscrew calculation and stepper config
    float Pitchtpi ; // used for imperial leadscrew calculation and stepper config
    void RotaryChanged(); //we need to declare the func above so Rotary goes to the one below
    RotaryEncoder Rotary(&RotaryChanged, 4, 5, 6 ); // Pins 4 (DT), 5 (CLK), 6 (SW)

    void RotaryChanged()
    {
      const unsigned int state = Rotary.GetState();
        if (state & DIR_CW)  
        Counter++;
        if (state & DIR_CCW)  
        Counter--;    
    }
      int buttonValue = LOW;
        Bounce bouncer = Bounce( BUTTON, 5 ); 
       
    void setup()
    {
      pinMode(BUTTON,INPUT_PULLUP);
      Serial.begin(9600);
      Serial.print("T.I.S.M"); // Death to art tour, featuring songs from their hit album "Great Truckin' Songs of the Renaissance "
      delay(500);
      display.begin();
      display.clearDisplay();
      display.setFont(&FreeSansBold12pt7b);
      display.setTextColor(SSD1306_WHITE);
      display.setCursor(10, 30);   //set the coordinates to start writing text
      display.print("T.I.S.M" );  //print the characters at location x,y
      display.display(); 
      delay(500);
    }

 

    void loop()
     {
      display.clearDisplay();
      display.setFont(&FreeSansBold12pt7b);
      display.setTextColor(SSD1306_WHITE);
      display.setCursor(10, 30);   //set the coordinates to start writing text
      display.print("Select" );  //print the characters at location x,y
      display.display(); 

   if ( bouncer.update() ) {
     if ( bouncer.read() == HIGH) {
       if ( buttonValue == LOW ) {
         buttonValue = HIGH;        //starts mm()
         Serial.println("high");
         mm();
       } else {
         buttonValue = LOW;        // starts tpi()
          Serial.println("low");
          tpi();
       }
       
     }
   }
}


    void mm()
    {
      Serial.println("void mm");
    if (LastCount != Counter)  
      {
      Serial.println(Counter);    
      Pitchmm = Counter / 100.00 ;  //Metric threads have dec point values. i.e 1.25mm 
      display.clearDisplay();
      display.setFont(&FreeSansBold12pt7b);
      display.setTextColor(SSD1306_WHITE);
      display.setCursor(10, 30);   //set the coordinates to start writing text
      display.print(Pitchmm );  //print the characters at location x,y
      display.setCursor(70, 30);
      display.print(" mm");
      display.display(); 
      mm();         
      }

    }
    void tpi()
    {
      Serial.println("void tpi");
          if (LastCount != Counter)  
      {
     Serial.println(Counter);    
      Pitchtpi = Counter;
      display.clearDisplay();
      display.setFont(&FreeSansBold12pt7b);
      display.setTextColor(SSD1306_WHITE);
      display.setCursor(10, 30);   //set the coordinates to start writing text
      display.print(Pitchtpi,0 );  //print the characters at location x,y
      display.setCursor(70, 30);
      display.print(" tpi");
      display.display();
      tpi();  
      }
    }

You are calling a function from within itself (twice) without break; or return. That should eventually slow then freeze memory.

Instead of 'changing loops' think of your issue more like a state machine based on 'mode', and depending on 'mode', do one function or the other.

Good point.

Below as a framework to demonstrate the use of a state machine.

#include <Bounce.h>

#define BUTTON 2  // was pin 6
Bounce bouncer = Bounce(BUTTON, 5);

// available modes
enum MODE
{
  SELECT,
  MM,
  TPI,
};

// startup mode
MODE mode = SELECT;

void setup()
{
  Serial.begin(115200);
  pinMode(BUTTON, INPUT_PULLUP);

  // needed to stabalise
  delay(10);
  // dummy read needed to clear the change on the input
  bouncer.read();
  Serial.println(F("mode = SELECT"));
}

void loop()
{
  // read button and update mode
  readButton();

  switch (mode)
  {
    case SELECT:
      break;
    case MM:
      mm();
      break;
    case TPI:
      tpi();
      break;
  }
}

/*
  read button and update mode
*/
void readButton()
{
  // if there was a change
  if (bouncer.update())
  {
    // and the button was released
    if (bouncer.read() == HIGH)
    {
      switch (mode)
      {
        case SELECT:
          Serial.println(F("Changing from SELECT to MM"));
          mode = MM;
          break;
        case MM:
          Serial.println(F("Changing from MM to TPI"));
          mode = TPI;
          break;
        case TPI:
          Serial.println(F("Changing from TPI to SELECT"));
          mode = SELECT;
          break;
      }
    }
  }
}

void mm()
{
}

void tpi()
{
}

Do NOT call tpi() from within itself nor call mm() from within itself (as mentioned by @xfpd).

If you have questions, ask.

Note:
button pin and baud rate are different from your setup

Well I got the following code to work nicely and do what I wanted it to do

Now it starts up with splash/welcome screen, then as soon as the enc is moved it displays the display in mm, press button again and displays value in tpi, then back to mm...and so on and so on...

Thanks for showing me how MODE works. I will be using that a lot more from now on

#include <RotaryEncoder.h>  //Rotary_Encoder_KY-040_Fixed-main/RotaryEncoder.h https://github.com/ownprox/Rotary_Encoder_KY-040_Fixed.....NOTE. this installs as RotaryEncoder.h, so make sure to remove any existing library
#include <Bounce.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Fonts/FreeSansBold12pt7b.h>
#define SCREEN_WIDTH 128     // OLED display width, in pixels
#define SCREEN_HEIGHT 32     // OLED display height, in pixels
#define OLED_RESET -1        // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C  ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
#define BUTTON 6             // was pin 6

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

int Counter = 0, LastCount = 0;  //uneeded just for test
float Pitchmm;                   // used for metric leadscrew calculation and stepper config
float Pitchtpi;                  // used for imperial leadscrew calculation and stepper config

void RotaryChanged();                           //we need to declare the func above so Rotary goes to the one below
RotaryEncoder Rotary(&RotaryChanged, 4, 5, 6);  // Pins 4 (DT), 5 (CLK), 6 (SW)

void RotaryChanged() {
  const unsigned int state = Rotary.GetState();
  if (state & DIR_CW)
    Counter++;
  if (state & DIR_CCW)
    Counter--;
}
int buttonValue = LOW;
Bounce bouncer = Bounce(BUTTON, 5);
enum MODE  // available modes
{
  MM,
  TPI,
};

MODE mode = MM;  // startup mode

void setup() {
  Serial.begin(9600);
  pinMode(BUTTON, INPUT_PULLUP);
  display.begin();
  delay(10);       // needed to stabalise
  bouncer.read();  // dummy read needed to clear the change on the input
  splash();
}
void splash() {
  display.clearDisplay();
  display.setFont(&FreeSansBold12pt7b);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(10, 30);
  display.print("T.I.S.M");  // Death to Art tour, featuring songs from their hit album "Great Truckin' Songs of the Renaissance "
  display.display();
  delay(500);
  loop();
}
void loop() {
  readButton();  // read button and update mode
  switch (mode) {
    case MM:
      mm();
      break;
    case TPI:
      tpi();
      break;
  }
}

/*
        read button and update mode
      */
void readButton() {
  // if there was a change
  if (bouncer.update()) {
    // and the button was released
    if (bouncer.read() == HIGH) {
      switch (mode) {
        case MM:
          Serial.println(F("Changing from MM to TPI"));
          mode = TPI;
          break;
        case TPI:
          Serial.println(F("Changing from TPI to MM"));
          mode = MM;
          break;
      }
    }
  }
}

void mm() {
  Serial.println("void mm");
  if (LastCount != Counter) {
    Serial.println(Counter);
    Pitchmm = Counter / 100.00;  //Metric threads have dec point values. i.e 1.25mm
    display.clearDisplay();
    display.setFont(&FreeSansBold12pt7b);
    display.setTextColor(SSD1306_WHITE);
    display.setCursor(10, 30);  //set the coordinates to start writing text
    display.print(Pitchmm);     //print the characters at location x,y
    display.setCursor(70, 30);
    display.print(" mm");
    display.display();
  }
}

void tpi() {
  Serial.println("void tpi");
  if (LastCount != Counter) {
    Serial.println(Counter);
    Pitchtpi = Counter;  // value in TPI
    display.clearDisplay();
    display.setFont(&FreeSansBold12pt7b);
    display.setTextColor(SSD1306_WHITE);
    display.setCursor(10, 30);  //set the coordinates to start writing text
    display.print(Pitchtpi);    //print the characters at location x,y
    display.setCursor(70, 30);
    display.print(" tpi");
    display.display();
  }
}

I suggest that you fix the indentation of your code using tools / auto format; as it is now it's a nightmare to follow.

It will not effect the code but will make it far easier to view it and to spot mistakes.

....I have been trying to remember that command...... :face_with_spiral_eyes: