0

I have some basic programming experience but I am a novice at both C and Arduino.

I messed around with the example LCD code to try to move a character around with the onboard keypad. I also wanted the actual move to occur only once the button is released, like you would expect from a keypad.

The code works, but I have a feeling all the empty WHILE loops inside the main loop() function I used are not the best practice.. :)

How did I do? Is there a more convenient/elegant solution I missed and can learn from?

Thanks, and sorry for the messy code!

void loop()
{
  lcd.clear();
  lcd.setCursor(posCol,posRow);      //initialized beforehand
  lcd.print("O");                    //random char to move
  lcdOld = btnNONE;

  while (read_LCD_buttons() == btnNONE)     //do nothing while nothing is pressed
  {
  }

  lcdOld = read_LCD_buttons();

  while (read_LCD_buttons() == lcdOld)     //do nothing while button is down
  {
  }

  switch (lcdOld)               // depending on which button was pushed, we perform an action
   {
   case btnRIGHT:
     {
     posCol++;
     break;
     }
   case btnLEFT:
     {
     posCol--;
     break;
     }
   case btnUP:
     {
     if (posRow == 1)
     {
        posRow = 0;
        break;
     }
     else
     {
     break;
     }
     }
   case btnDOWN:
     {
     if (posRow == 0)
     {
        posRow = 1;
        break;
     }
     else
     {
     break;
     }
     }
   case btnSELECT:
     {
     break;
     }
     case btnNONE:
     {
     break;
     }
 }  
}
2
  • This is fine, as long as you don't want you program to do anything else at the same time (like blinking an led for example). If you want that, you could just make the code remember the last button states, and only run the switch part of the code when any button goes from not being pressed, to being pressed. (PS remember to take button bounce into account, as that can mess things up. Not sure if read_LCD_buttons() already takes care of that)
    – Gerben
    Dec 11 '17 at 10:46
  • I know it is been a while since you post this post but is there any way you can repost the whole source code? Oct 3 at 8:42
3

You could encapsulate the logic of detecting a button release into its own function:

// Return the button that was just released, or btnNONE.
int releasedButton()
{
    static int last_button = btnNONE;
    int previous_button = last_button;
    last_button = read_LCD_buttons();
    if (last_button == btnNONE)
        return previous_button;
    else
        return btnNONE;
}

Then the logic in the loo gets simplified:

void loop()
{
    switch (releasedButton()) {
        ...
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.