Shop OBEX P1 Docs P2 Docs Learn Events
toggle output of propeller with one input switch — Parallax Forums

toggle output of propeller with one input switch

gregmazarakisgregmazarakis Posts: 15
edited 2014-11-28 18:52 in Propeller 1
I started to write a program in C using simpleIDE with different in- and outputs.
I define the inputs as integers like 'int button1=input(12);" and setting the output 17 with "high(17);"
I would like to have the same input toggling the output so that it comes on with the first push action and goes off with the following push-action.
Can anyone give me an example of how to do this??

Comments

  • KyeKye Posts: 2,200
    edited 2014-11-28 18:52
    Here's the basic idea:
    #include "simpletools.h"
    
    bool buttonStates[32]; // startup zero
    bool buttonPressed[32]; // startup zero
    bool buttonReleased[32]; // startup zero
    
    void debounceButtons()
    {
        static int buttonShifts[32]; // startup zero
    
        for(int i = 0; i < 32; i++)
        {
            buttonShifts = (buttonShifts << get_state(i));
    
            // Seen 32 one samples and was previously low
            if( (!(~buttonShifts)) && (!buttonStates[i]))
            {
                buttonStates[i] = true;
    
                if(!buttonPressed[i)]
                {
                    buttonPressed[i] = true;
                }
            }
    
            // Seen 32 zero samples and was previously high
            if( (!buttonShifts) && buttonStates[i])
            {
                buttonStates[i] = false;
    
                if(!buttonReleased[i])
                {
                    buttonReleased[i] = true;
                }
            }
        }
    }
    
    void getButtonState(int pin)
    {
        return buttonStates[pin & 0x1F];
    }
    
    void getButtonPressed(int pin) // returns true once per button press
    {
        if(buttonPressed[pin & 0x1F])
        {
            buttonPressed[pin & 0x1F] = false;
    
            return true;
        }
    
        return false;
    }
    
    void getButtonReleased(int pin) // returns true once per button release
    {
        if(buttonReleased[pin & 0x1F])
        {
            buttonReleased[pin & 0x1F] = false;
    
            return true;
        }
    
        return false;
    }
    
    int main()
    {
        low(17);
    
        for(;;)
        {
            waitcnt((CLKFREQ/1000)+CNT);
    
            debounceButtons();
    
            if(getButtonPressed(12))
            {
                toggle(17);
            }
        }
    }
    
Sign In or Register to comment.