I've been at this for about a month, still very new at learning. I think I am beginning to understand a little more and have fixed most of the issues I've had so far. (usually when I fix 1, 2 more pop up.) Anyway, its all good fun!
A bit of background at my shit code, my current end goal is that when I press the button the led turns on and a single key is pressed. When I press it again the led turns off and that same key is pressed again.
Currently, I just get a constant stream of the key regardless of if I've pressed or not.
I am using an Arduino Leonardo. Let me know where I went wrong!
//Pushing a Button Start/Stop LED
//constants
const int buttonPin = 4; // Indicates the Pin location of the button.
const int ledPin = 7; // Indicates the Pin location of the LED.
//variables
int ledState = HIGH; // Indicates the initial (current?) state of the LED.
int buttonState; // Indicates when the button is pressed (?)
int lastButtonState = LOW; // Indicates the previous state of the button (?)
//long variables
long lastDebounceTime = 0; // Indicates the last time the the button was pressed (?)
long debounceDelay = 25; // Indicates the delay of time such that the button press is not accidentally registered.
void setup() {
pinMode(buttonPin, INPUT); // Indicates the button being pushed it will cause
pinMode(ledPin, OUTPUT); // this action to occur.
digitalWrite(ledPin, ledState); // (?)
digitalWrite(buttonPin, HIGH); // (?)
Keyboard.begin(); // Indicates that a button press will register as key input.
}
void loop() {
int reading = digitalRead(buttonPin); // Indicates when the button is pressed
if (reading != lastButtonState) { // and if that button press is different than the previous buttons state
lastDebounceTime = millis(); // and it is outside of the delay of time to avoid accidental button registration
}
if ((millis() - lastDebounceTime) > debounceDelay) { // (?)
if (reading != buttonState) { // (?)
buttonState = reading; // (?)
if (buttonState == HIGH) { // Indicates that if the button was indeed pressed that
ledState = !ledState; // the LED state should change.
}
}
}
digitalWrite(ledPin, ledState); // Indicates the LED should turn on or off
lastButtonState = reading;
reading = digitalRead(buttonPin); // Indicates when the button is pressed
if (reading != lastButtonState) { // and if that button press is different than the previous buttons state
lastDebounceTime = millis(); // and it is outside of the delay of time to avoid accidental button registration
}
if ((millis() - lastDebounceTime) > debounceDelay) { // (?)
if (reading != buttonState) { // (?)
buttonState = reading; // (?)
if (buttonState == HIGH) { // Indicates that if the button was indeed pressed that
buttonState = !buttonState; // (?)
}
}
}
Keyboard.write('N'); // Indicates the character pressed.
delay(100); // Indicates the amount time before the character can be written again.
lastButtonState = reading;
}