Go Down

Topic: Toggle TO momentary button press code: (Read 297 times) previous topic - next topic

teknogeek1300

Googled around a lot and only found the opposite, turning temporary button presses into toggles.

This code simulates a button press for a desired amount of time when the toggle switch is flipped on, then presses again when the toggle is flipped off.

The purpose of this is for games that do not support a press/hold button feature.

PULLDOWN so no debouncing required.

Code: [Select]

char switch1 = 0; //name of fist switch
char switch2 = 0; //name of second switch
void setup() {
  pinMode(13, OUTPUT); //onboard LED to confirm toggles are working
  pinMode(8, INPUT_PULLUP); //pin first toggle is connected to
  pinMode(7, INPUT_PULLUP); //pin second toggle is connected to
}
void loop() {
  if (digitalRead(8) == LOW && (switch1 == 0)){
     digitalWrite(13, HIGH);
     delay(90); // how long the button press will occur
     digitalWrite(13, LOW);
     switch1 = 1; // changes the switches char so the switch will not automatically loop
  }
  if (digitalRead(8) == HIGH && (switch1 == 1)){
     digitalWrite(13, HIGH);
     delay(90); // how long the button press will occur
     digitalWrite(13, LOW);
     switch1 = 0;
  }

  if (digitalRead(7) == LOW && (switch2 == 0)){
     digitalWrite(13, HIGH);
     delay(90); // how long the button press will occur
     digitalWrite(13, LOW);
     switch2 = 1; // changes the switches char so the switch will not automatically loop
  }
  if (digitalRead(7) == HIGH && (switch2 == 1)){
     digitalWrite(13, HIGH);
     delay(90); // how long the button press will occur
     digitalWrite(13, LOW);
     switch2 = 0;
  }
}

sobNorway


el_supremo

There's no documentation which explains how this code would be used in real life. For example, why do you have two toggle switches, both of which toggle the same output? How is a game going to know what's what?
How would you connect this to a game? Have you actually connected it to a game? Which one?
The pin numbers and the delay values are all hard-coded - not good practice.

Quote
PULLDOWN ...
Eh? You're using INPUT_PULLUP.

Quote
... so no debouncing required
Nonsense. You are debouncing the switches, you just don't realize it.

Pete
Don't send me technical questions via Private Message.

Go Up