Using a toggle switch for a single key press.

I am trying to set up a toggle switch that will press 'T' when flipped on and 'T' when flipped off (there is a gif attached that illustrates what I am trying to accomplish). I have gotten my code to recognize the state change, but the output acts like the 'T' button is being held down instead of pressed once. Serial monitor was added in to show that it does recognize the state change. My code is below:

#include <Keyboard.h>

const int toggle1 = 8;
int toggle1State = 0;
int lastToggle1State = 0;

void setup()
{ 

  pinMode(toggle1, INPUT);
 
  Serial.begin(9600);
  Keyboard.begin();

}
//
void loop()
{
  toggle1State = digitalRead(toggle1);
 
  if (toggle1State != lastToggle1State)
  {
    if (toggle1State == HIGH)
    {
      Serial.write('1');
      //Keyboard.press('1');
      delay(500);
    }
    else if (toggle1State == LOW)
    {
      Serial.write('2');
      //Keyboard.press('2');
      delay(500);
    }
    delay(50);
    //Keyboard.releaseAll();
  }

  lastToggle1State = toggle1State;

  if (toggle1State == lastToggle1State)
  {
    if (toggle1State == HIGH)
    {
      Serial.write('1');
      //Keyboard.press('1');
      delay(500);
    }
    else if (toggle1State == LOW)
    {
      Serial.write('2');
      //Keyboard.press('2');
      delay(500);
    }   
    delay(50);
    //Keyboard.releaseAll();
  }
 //Keyboard.releaseAll();
 
}

2120B.gif

2120B.gif

Try deleting everything after lastToggle1State = toggle1State; .

Excepting, of course, the closing curly brace of loop().

No, that made it print '121212121212121....' and did not register any inputs. I think my problem is how to get Keyboard.press('1') to only register 1 button press instead of 1111111111111.

You cut and pasted some extra. This is your program with a few changes and deleting the hiccup. It prints '2' when you ground pin 8, and '1' when you let it go high.

I just took out all the keyboard stuff, this ran on a UNO.

//#include <Keyboard.h>

const int toggle1 = 8;
int toggle1State = 0;
int lastToggle1State = 0;

void setup()
{ 

  pinMode(toggle1, INPUT_PULLUP);
 
  Serial.begin(9600);
//  Keyboard.begin();

}
//
void loop()
{
  toggle1State = digitalRead(toggle1);
 
  if (toggle1State != lastToggle1State)
  {
    if (toggle1State == HIGH)
    {
      Serial.write('1');
      //Keyboard.press('1');
      delay(500);
    }
    else if (toggle1State == LOW)
    {
      Serial.write('2');
      //Keyboard.press('2');
      delay(500);
    }
    delay(50);
    //Keyboard.releaseAll();
  }

  lastToggle1State = toggle1State;

}

HTH

a7