Toggle switch on Arduino

Hi,

I'm using toggle switch with arduino and I want to achieve press button (only once) when toggle switch is active:

   if(digitalRead(7) == 0)
    {
      Keyboard.write('7');
      delay(200);
      if(digitalRead(7) != 0)
        {
          Keyboard.releaseAll();
        }      
    }             

but in this scenario button is constantly pressed. How to achieve that button will be pressed only once, but same time toggle switch is active?

Please slow down and tell us what your requirements are ?


Always show us a good schematic of your proposed circuit.
Show us a good image of your ‘actual’ wiring.
Give links to components.

1 Like

try using a flag

I'm ussing toggle switch to type a '7' when button is active. But he keeps repeating the same "7". What I want to achieve is that it will only type or press once even if the switch is active. I edited the code I added.

bool state=0;

if(digitalRead(7) == 0 && state==0)
    {
      Keyboard.write('7');
      state=1;
      delay(50);
   }

      if(digitalRead(7) != 0)
        {
          Keyboard.releaseAll();
          state=0;
        }      
 

This should work as you said

Post the complete sketch to see how we can help.

Can you post a small schematic showing the button/switch and how it is wired. Please include all power sources.

To many braces }

Oops . i fixed it. Thanks

We do not know your complete program, if blocking for the time you press the button is ok, this would do it also

if(digitalRead(7) == 0)
    {
      Keyboard.write('7');
      delay(20);  //Poor man's debouncing 
      Keyboard.releaseAll();  
      while(digitalRead(7) == 0) {}; \\Wait until button released 
    }             

It worked, thank you.
But why it is not working with if inside if?:

bool state=0;

if(digitalRead(7) == 0 && state==0)
    {
      Keyboard.write('7');
      state=1;
      delay(50);
      if(digitalRead(7) != 0)
        {
          Keyboard.releaseAll();
          state=0;
        }      
   }

I'm just curious.

Here I first initialise a variable name "state".
Now if(digitalRead(7) == 0 && state==0) checks if you have pressed the button on pin 7 and the state== 0 assure that this is first time functions is executing. After that the state=1 represent that the function Keyboard.write('7') has already executed. And the statement if(digitalRead(7) == 0 && state==0) is no longer true.

Now when you release the button the second statement if(digitalRead(7) != 0) reset state to 0. And the loop continues.

That because only one statement can be true at a time. Either digitalRead(7) != 0 or digitalRead(7) == 0

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.