Button press

Hi
In my code I have a lot of button press to check… this works BUT it looks a bit UGH.

 buttonState = digitalRead(depthup_button);
  if (buttonState == HIGH) {     
   depth ++;   
   buttonState = 0;  
  } 
   buttonState = digitalRead(depthdown_button);
  if (buttonState == HIGH) {     
   depth --; 
   buttonState = 0;  
if (depth > 255) { depth = 255; }   //checks the limmets
   if (depth < 0) { depth = 0; }

Is there any way I can make this more efficient ??.

Regards Antony

I think the compiler will optimize that stuff anyways.

But you are allowed to put function calls inside the expression for the if statements

Also you don't have to explicitly reset buttonState to 0, but again, the compiler will probably see that and optimize it out for you

First thing is to use the auto format tool in the IDE to fix the tabbing.

buttonState = 0;
}
buttonState = digitalRead(depthdown_button);

Why bother changing the value of buttonState to 0 if you are just going to change it in the next instruction?

Without seeing the entire sketch, I'm not sure I understand what you are trying to accomplish, so I can't offer much in terms of optimization.

You need to test for transitions. That is, is the button HIGH, when it was LOW before. Otherwise in the brief time you hold down a button, the depth variable will rocket up so high it will probably overflow and be all over the place.

Hi.
Thanks for all the info.. It's a learning curve that not that easy at 62.
But some good pointers for me.
Nick. The depth required will be displayed so I need to be able to ask the RoV to dive to a depth.
In the Sub unit the controler will read the required depth and auto adjust with a pressure sensor.
I was hopeing to use a pot with a centre indent for this..But cannot find one.

Many thanks Antony

I was hopeing to use a pot with a centre indent for this…But cannot find one.

That would be the definition of a joystick. Hard to believe you can’t find one.

And, you really do need to trigger only on transitions. It is not that difficult.

int prevState = LOW;

void loop()
{
   int currState = digitalRead(somePin);
   if(currState != prevState)
   {
      // A transition occurred (from pressed to released or from released to pressed)
   }
   prevState = currState;
}

To determine whether the transition is from pressed to released, or from released to pressed, you only need to look at the current state. If it is pressed, the transition was from released to pressed. Otherwise, the transition was from pressed to released.

You need, of course, to decide which transition should trigger the increment/decrement operation.

Hi Paul.
This is what I am looking for But the cost is way to high.
http://www.apem.co.uk/pdf/Joysticks%202011/TW_APEM_low%20res.pdf
Or some thing similar would be fine.
Then I can ask either a fast decent or a slow decent.

Regards Antony.

Keep the up down buttons and add a regular pot. Basically, use the pot for speed control but, the buttons for direction. Set pot to minimum for slow action and max for fast action.

Have a look at my Button library here: https://github.com/JChristensen/Button

See the “UpDown” example that comes with the library, I think it is very similar to what you want to do.

/*----------------------------------------------------------------------*
 * Example sketch for Arduino Button Library by Jack Christensen        *
 *                                                                      *
 * An example that uses both short and long button presses to adjust    *
 * a number up and down, between two limits. Short presses increment    *
 * or decrement by one, long presses repeat at a specified rate.        *
 * Every time the number changes, it is written to the serial monitor.  *
 *                                                                      *
 * This work is licensed under the Creative Commons Attribution-        *
 * ShareAlike 3.0 Unported License. To view a copy of this license,     *
 * visit http://creativecommons.org/licenses/by-sa/3.0/ or send a       *
 * letter to Creative Commons, 171 Second Street, Suite 300,            *
 * San Francisco, California, 94105, USA.                               *
 *----------------------------------------------------------------------*/

#include <Button.h>        //https://github.com/JChristensen/Button

#define DN_PIN 2           //Connect two tactile button switches (or something similar)
#define UP_PIN 3           //from Arduino pin 2 to ground and from pin 3 to ground.
#define PULLUP true        //To keep things simple, we use the Arduino's internal pullup resistor.
#define INVERT true        //Since the pullup resistor will keep the pin high unless the
                           //switch is closed, this is negative logic, i.e. a high state
                           //means the button is NOT pressed. (Assuming a normally open switch.)
#define DEBOUNCE_MS 20     //A debounce time of 20 milliseconds usually works well for tactile button switches.

#define REPEAT_FIRST 500   //ms required before repeating on long press
#define REPEAT_INCR 100    //repeat interval for long press
#define MIN_COUNT 0
#define MAX_COUNT 59

Button btnUP(UP_PIN, PULLUP, INVERT, DEBOUNCE_MS);    //Declare the buttons
Button btnDN(DN_PIN, PULLUP, INVERT, DEBOUNCE_MS);

enum {WAIT, INCR, DECR};              //The possible states for the state machine
uint8_t STATE;                        //The current state machine state
int count;                            //The number that is adjusted
int lastCount = -1;                   //Previous value of count (initialized to ensure it's different when the sketch starts)
unsigned long rpt = REPEAT_FIRST;     //A variable time that is used to drive the repeats for long presses

void setup(void)
{
    Serial.begin(115200);
}

void loop(void)
{
    btnUP.read();                             //read the buttons
    btnDN.read();
    
    if (count != lastCount) {                 //print the count if it has changed
        lastCount = count;
        Serial.println(count, DEC);
    }
    
    switch (STATE) {
        
        case WAIT:                                //wait for a button event
            if (btnUP.wasPressed())
                STATE = INCR;
            else if (btnDN.wasPressed())
                STATE = DECR;
            else if (btnUP.wasReleased())         //reset the long press interval
                rpt = REPEAT_FIRST;
            else if (btnDN.wasReleased())
                rpt = REPEAT_FIRST;
            else if (btnUP.pressedFor(rpt)) {     //check for long press
                rpt += REPEAT_INCR;               //increment the long press interval
                STATE = INCR;
            }
            else if (btnDN.pressedFor(rpt)) {
                rpt += REPEAT_INCR;
                STATE = DECR;
            }
            break;

        case INCR:                                //increment the counter
            count = min(count++, MAX_COUNT);      //but not more than the specified maximum
            STATE = WAIT;
            break;

        case DECR:                                //decrement the counter
            count = max(count--, MIN_COUNT);      //but not less than the specified minimum
            STATE = WAIT;
            break;
    }
}

Hi.
Now that's a nice idea. Buttons that the longer I hold down the faster the movement.. That's so cool.
I would like to use this in my setup.
Might add it tonight..

Thanks Jack

antony1876:
Hi.
Now that's a nice idea. Buttons that the longer I hold down the faster the movement.. That's so cool.
I would like to use this in my setup.
Might add it tonight..

Thanks Jack

Hope it works for you, let me know!

Joysticks don't have to be expensive. An analog one (two pots plus down button) is here for 5 bucks:

http://iteadstudio.com/store/index.php?main_page=product_info&cPath=18&products_id=435

Hi Pylon.
Yes I have one the same but to sensitive and not much use for my application.
I do like the Button press idea best.
It will work like this :- I want to dive..I press the hold the dive button.
Sub dives until I release dive button.
Sub reads pressure sensor.
Dive thruster stops..
Sub then maintains current depth with help from pressure sensor.
I can then do quick button presses to adjust final wanted depth.

Thanks for all the valued inputs.
Regards Antony