implementing toggle switch in arduino

Thread Starter

justtrying

Joined Mar 9, 2011
439
I need to program a toggle switch in arduino to be able to toggle between two modes. As a start I played around toggling LEDs and it worked out fine but I am having issues using it to switch between different sections of my program. Within the program a user should have a choice to go into either learn mode or trigger mode when using the device.

Here is what I have as a basic program:

Rich (BB code):
byte switchPin = 2;        //pin to which switch is connected 
byte ledPin = 13;

volatile boolean trigger = LOW; //interrupt attached to the pin

void setup()
{
  attachInterrupt(0, interrupttrigger, LOW); //digital pin 2 is interrupt 0
  pinMode(ledPin,OUTPUT);
}

void loop()
{
  delay(20); //wait to debounce the switch
  
  if (trigger = !trigger) //check if interrupt was triggered
    {
       LED(); //go execute the function
       //use this to execute one function in one state
    }
  else
    {
        analogWrite(ledPin, 0); //turn LED off 
        //execute another function in another state
    }
}

void LED()

{
  delay(200);
  while(trigger == LOW)
    {
      digitalWrite(ledPin, HIGH);
    }
}  

void interrupttrigger()
{
  if(trigger == LOW)  //reset switch
    {
      trigger = HIGH;
    }
  else
    {
      trigger = LOW;
    }
}
I thought that I should be able to replace LEDs with my respective functions, but it does not seem to be working. I've tried a few other things, but they only end in one mode stopping and restarting. I would appreciate any suggestions (except replacing this with a push button :))
 
Hi, have you looked at the example sketch for toggling between two states. In my Arduino IDE, it's at File -> examples -> digital -> debounce

I'm only new to this game, but in all of the working sketches that I've seen so far, there is nothing after the end of loop() ...

Hope this helps,
Rob
 

chrisw1990

Joined Oct 22, 2011
551
im not arguing lol, i just wondered, iv always just put them at the end of functions.. if anything to just say "done" but each to their own, as long as the code works!:D
 

Thread Starter

justtrying

Joined Mar 9, 2011
439
thanks, I got it to work. I think ideally I would want to use interrupts, but not enough time to sort it out.

About return, arduino is interesting that way, almost "sloppy" as it contains no requirement to have a return at the end of a function.
 

hgmjr

Joined Jan 28, 2005
9,027
You would need a return statement in a function that returns a value rather than void.

simple example:

Rich (BB code):
unsigned int get_product(unsigned char a, unsigned char b){
 
       return(a*b);
 
}
hgmjr
 
Any chance of posting your final sketch here, plus a few words about how it works?

Some of the official examples do indeed have functions after the end of loop(), so that's something new I've learned about Arduinos :)
 
Top