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();
}