How do i setup a Toggle Switch?

09 Jun 2012

I've been scouring this site for a while now and i just can't find a way to use a toggle switch?

I cant find any code for this at all for example

i have a switch in the off and i want to flick it over to the on to allow it to run another piece of code, can someone please show me an example of an if switch is on then else

the switch is a toggle switch with two pins SPST Thanks guys!

10 Jun 2012

Hi Matthew,

Here is a code example that would run different code each time you switched the switch:

Import program

00001 // run some code based on switching a switch (changing a pin state)
00002 
00003 #include "mbed.h"
00004 
00005 DigitalIn toggle(p5);
00006 DigitalOut myled(LED1);
00007 
00008 void toggle_on() {
00009     for(int i=0; i<10; i++) {
00010         myled = !myled;
00011         wait(0.2);
00012     }
00013 }
00014 
00015 void toggle_off() {
00016     // do nothing
00017 }
00018 
00019 int main() {
00020     while(1) {
00021         while(!toggle); // wait while toggle == 0
00022         toggle_on();
00023         while(toggle);  // wait while toggle == 1
00024         toggle_off();
00025     }
00026 }

You'd wire the switch between p5 and 3.3v/VOUT.

Hope that helps,

Simon

10 Jun 2012

Thank you simon you're awesome! only started using mbed yesterday and i like it better than the arduino and picaxe! btw your toggle off should be the same for example

myled = !myled; turns it off and myled = !myled; turns it on

This is because of the value stored in toggle(p5)

all i need now is to figure out my USBSerial char buffer :(