text:
Multi Level Button Menu
Have been working on a Button Menu for a while now and can't break thru to the 3rd level, which in theory would give access to levels 4/5/6/etc.
It's layed out long hand, I'll neaten the code up after its working.
Could you pls have a look and see if you can access level 3....
Also if there is an alternative for multi level menus, happy to look at those also, just after something that works, have tried dozens that i have found on the web.....either no sketch with the video(how i hate that) or sketch just doesn't work period.
Thanks in advance
Doug
    /*
Description : Simple Menu function on LCD
          Button Function:
            Up/Down - change Menu Page
            Select - enter page
            Left - Exit

Link: http://youtu.be/cMqif5ICS5M

+++++++++++++++++++++++++++++++++++++++++++++++++++*/
*/
#include <LiquidCrystal_I2C.h> //from newliquidcrystal library
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

int keypad_pin = A0;
int keypad_value = 0;
int keypad_value_old = 0;

bool menu2 = false;
char btn_push;

int selection1 = 0;
int selection2 = 0;

int mainMenuPage = 1;
int mainMenuPageOld = 1;
int mainMenuTotal = 4;

int levelMenuPage = 1;
int levelMenuPageOld = 1;
int levelMenuTotal = 4;

void setup()
{
  Serial.begin(9600);
lcd.begin(20, 4);  //Initialize a 2x16 type LCD

MainMenuDisplay();
delay(1000);

}
void loop()
{
MainmenuBtn();

if((btn_push == 'S')&&(menu2 == false))//enter selected menu
{
  Serial.println("i'm here");
    WaitBtnRelease();
    switch (mainMenuPage)
    {
        case 1:
          MenuA();
          break;
        case 2:
          MenuB();
          break;
        case 3:
          MenuC();
          break;
        case 4:
          MenuD();
          break;
    }

      MainMenuDisplay();
      WaitBtnRelease();
  }
  else
{
   if((btn_push == 'S')&&(menu2 == true))//enter selected menu
{
  LevelmenuBtn();
    WaitBtnRelease();
    switch (levelMenuPage)
    {
        case 1:
          MenuA2();
          break;
        case 2:
          MenuB2();
          break;
        case 3:
          MenuC2();
          break;
        case 4:
          MenuD2();
          break;
    }

      LevelMenuDisplay();
      WaitBtnRelease();
  }

  delay(10);
}
}
//--------------- End of loop() loop ---------------------
void MainmenuBtn()
{
  btn_push = ReadKeypad();
WaitBtnRelease();
if(btn_push == 'U')
{
    mainMenuPage++;
    if(mainMenuPage > mainMenuTotal)
      mainMenuPage = 1;
      Serial.println(mainMenuPage);
}
else if(btn_push == 'D')
{
    mainMenuPage--;
    Serial.print(mainMenuPage);
    if(mainMenuPage == 0)
      mainMenuPage = mainMenuTotal;
      Serial.println(mainMenuPage);
}

if(mainMenuPage != mainMenuPageOld) //only update display when page change
{
    MainMenuDisplay();
    mainMenuPageOld = mainMenuPage;
}
}
void LevelmenuBtn()
{
  btn_push = ReadKeypad();
WaitBtnRelease();
if(btn_push == 'U')
{
    mainMenuPage++;
    if(levelMenuPage > levelMenuTotal)
      levelMenuPage = 1;
      Serial.println(levelMenuPage);
}
else if(btn_push == 'D')
{
    levelMenuPage--;
    Serial.print(levelMenuPage);
    if(levelMenuPage == 0)
      levelMenuPage = levelMenuTotal;
      Serial.println(levelMenuPage);
}

if(levelMenuPage != levelMenuPageOld) //only update display when page change
{
    LevelMenuDisplay();
    levelMenuPageOld = levelMenuPage;
}
}
void MainMenuDisplay()
{
lcd.clear();
lcd.setCursor(0,0);
switch (mainMenuPage)
{
    case 1:
      lcd.print("1. Menu A");
      break;
    case 2:
      lcd.print("2. Menu B");
      break;
    case 3:
      lcd.print("3. Menu C");
      break;
    case 4:
      lcd.print("4. Menu D");
      break;
}
}
void LevelMenuDisplay()
{
lcd.clear();
lcd.setCursor(0,0);
switch (levelMenuPage)
{
    case 1:
      lcd.print("1. Menu A2");
      break;
    case 2:
      lcd.print("2. Menu B2");
      break;
    case 3:
      lcd.print("3. Menu C2");
      break;
    case 4:
      lcd.print("4. Menu D2");
      break;
}
}
void MenuA()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu A");
 menu2 = true;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu A here
 selection1=1;
 Serial.print("Selection1=");
 Serial.println(selection1);
}
}
void MenuA2()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu A2");
menu2 = false;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu A here
 selection2=1;
 Serial.print("Selection2=");
 Serial.println(selection2);
}
}
void MenuB()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu B");
menu2 = true;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu B here

 selection1=2;
 Serial.print("Selection1=");
 Serial.println(selection1);
}
}
void MenuB2()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu B2");
menu2 = false;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu B here
 selection2=2;
 Serial.print("Selection2=");
 Serial.println(selection2);
}
}
void MenuC()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu C");
menu2 = true;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu C here
 selection1=3;
 Serial.print("Selection1=");
 Serial.println(selection1);
}
}
void MenuC2()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu C2");
menu2 = false;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu C here
 selection2=3;
 Serial.print("Selection2=");
 Serial.println(selection2);
}
}
void MenuD()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu D");
menu2 = true;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu D here
 selection1=4;
 Serial.print("Selection1=");
 Serial.println(selection1);
}
}
void MenuD2()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu D2");
menu2 = false;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu D here
 selection2=4;
 Serial.print("Selection2=");
 Serial.println(selection2);
}
}

char ReadKeypad()
{
/* Keypad button analog Value
no button pressed 1023
nul     <450
select  <400
left    <350
down    <290
up      <190
right   <50
*/
keypad_value = analogRead(keypad_pin);

if(keypad_value < 50)
return 'R';
else if(keypad_value < 190)
return 'U';
else if(keypad_value < 290)
return 'D';
else if(keypad_value < 350)
return 'L';
else if(keypad_value < 400)
return 'S';
else if(keypad_value < 450)
return 'N';

}

void WaitBtnRelease()
{
  while( analogRead(keypad_pin) < 600){}
}

Doug, please give us the setup. Are there just 3 buttons with BUTTON1 selecting the MAINMENU and BUTTON2 scrolling UP the menu selected by BUTTON1 and BUTTON3 scrolling DOWN the menu selected by BUTTON1. And by pressing again BUTTON1,the selection is SET - as in the layout below:
BUTTON1 selects CURRENT from selections like VOLTAGE, CURRENT, AMPHR. BUTTON2 selects UPWARDS 100mA, 300mA, 500mA, 750mA, 1000mA
BUTTON3 selects DOWNWARDS 100mA, 300mA, 500mA, 750mA, 1000mA
Finally, PRESSING BUTTON1 fixes on the selection made by either BUTTON2 OR BUTTON3. We need to know how many buttons there are an

please give us the setup. Are there just 3 buttons with BUTTON1 selecting the MAINMENU and BUTTON2 scrolling UP the menu selected by BUTTON1 and BUTTON3 scrolling DOWN the menu selected by BUTTON1. And by pressing again BUTTON1,the selection is SET - as in the layout below: BUTTON1 selects CURRENT from selections like VOLTAGE, CURRENT, AMPHR. BUTTON2 selects UPWARDS 100mA, 300mA, 500mA, 750mA, 1000mA BUTTON3 selects DOWNWARDS 100mA, 300mA, 500mA, 750mA, 1000mA Finally, PRESSING BUTTON1 fixes on the selection made by either BUTTON2 OR BUTTON3.

We need to know how many buttons there are and what each button do, and which button FIXES the selection made. Thanks, George

Look to this section of the code " read buttons  " and you will see that I have listed the buttons used and their purpose..I have included the 6th button NULL to indicate that you can have more buttons than I have actually used (5) if required. Please read and study the code and comments as all the info you need is their. The final code is listed below and has the header containing "/ Rebuilt by Doug 07/02/2017 Australia." This is tested and works

Ok...nobody bought into this and I understand why...menus have been done to death, but not being one to quite I have answered my own question.
Here is a simple, fool proof button menu, that i think has NO limit in depth.
I have just tested this before posting, so if you don't get it to work, check your wiring. instructions at the bottom of the sketch.
    /* Rebuilt by Doug 07/02/2017 Australia.
 * This is a bare bones menu using buttons to navigate and select, there are no special libraries,
 * I am using an I2C LCD2004, but any display will work with minor mods. This has been translated from,
 * I believe Slovakian, that was fun, stripped down and modified for button control, I have found that
 * buttons are less picky than rotary encoders, even the good ones, just my experience.
 * I believe that I have removed all unnecessary script, but I may have missed some.
 * look at the last 2 --page()-- sections for instruction on extending down even further, I don't think
 * that there is a limit to how many levels you can have, how many do you really need.
 * The original sketch is from: Stanislav Petrek of Slovakia, you can find sketch on YouTube comments.
 * https://www.youtube.com/watch?v=gIP29m12wjQ&t=41s
 * Have fun with the translation  ;-}
 * The last thing I did before posting was to relaod and test this sketch, so it works.
 */
#include <LiquidCrystal_I2C.h> //from newliquidcrystal library
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

// menu system
int poz = 0; //  cursor position on actual page
int poz_max = 1;
int poz_min = 0;

int pozOld = 0;
int pozNew = 0;

int page = 0; //  actual page
int page_max = 1;
int page_min = 0;

int press = 0;
int press_max = 1;

int keypad_pin = A0;                      //analoge A0 to sense button values.
int keypad_value = 0;
int keypad_value_old = 0;

//bool menu2 = false;
char btn_push;
//****************************************************************setup*****************************************
void setup() {
Serial.begin(9600);
lcd.begin(20, 4);
lcd.clear();
lcd.home();
}
//************************************************************loop************************************************
void loop() {
MainmenuBtn();
if (btn_push == 'S') //enter selected menu
{
press++;
delay(250);
if (press > press_max) {
  press = 0;
}
}
// page select
switch (page) {

case 0:
  page0();
  break;
case 1:
  page1();
  break;
case 2:
  page2();
  break;
case 3:
  page3();
  break;
case 4:
  page4();
  break;
case 5:
  page5();
  break;
}
}
//****************************************************up/down************************************************
void MainmenuBtn()
{
btn_push = ReadKeypad();
WaitBtnRelease();
if (btn_push == 'U')
{
poz++;
if (poz > poz_max) {
  poz = poz_max;
}
}
else if (btn_push == 'D')
{
poz--;
if (poz < poz_min) {
  poz = poz_min;
}
}
pozNew = poz;
if (pozNew != pozOld) { //only update display when page change
pozOld = pozNew;
}
}
//*************************************************************read buttons***********************************
char ReadKeypad()
{
/* Keypad button analog Value
no button pressed 1023
*********************adjust these values to suit your keypad***********************
nul     >400
select  <400
left    <350
down    <290
up      <190
right   <50
*/
keypad_value = analogRead(keypad_pin);
if (keypad_value < 50)
return 'R';
else if (keypad_value < 190)
return 'D';
else if (keypad_value < 290)
return 'U';
else if (keypad_value < 350)
return 'L';
else if (keypad_value < 400)
return 'S';
else if (keypad_value > 400)
return 'N';
}
//********************************************************button release*************************************
void WaitBtnRelease()
{
while ( analogRead(keypad_pin) < 600) {}
}
//*******************************************************Front Page 0*******************************************
void page0() {
poz_min = 0;
poz_max = 3;
press_max = 1;

lcd.setCursor(0, 0);
lcd.print("Pg1 Pg2 Pg3 Pg4     ");
lcd.setCursor(0, 2);
lcd.print("                    ");
lcd.setCursor(0, 3);
lcd.print("                    ");

switch (poz)
{
case 0:
  lcd.setCursor(0, 1);
  lcd.print("---                 ");
  if (press == 1) {
    press = 0;
    poz = 0;
    page = 1;
  }
  break;
case 1:
  lcd.setCursor(0, 1);
  lcd.print("    ---             ");
  if (press == 1) {
    press = 0;
    poz = 0;
    page = 2;
  }
  break;
case 2:
  lcd.setCursor(0, 1);
  lcd.print("        ---         ");
  if (press == 1) {
    press = 0;
    poz = 0;
    page = 3;
  }
  break;
case 3:
  lcd.setCursor(0, 1);
  lcd.print("            ---     ");
  if (press == 1) {
    press = 0;
    poz = 0;
    page = 4;
  }
  break;
}
}
//*************************************************Pages 1*****************************************
void page1() {
poz_min = 0;
poz_max = 2;
press_max = 1;

lcd.setCursor(0, 0);
lcd.print("Page1               ");
lcd.setCursor(0, 1);
switch (poz) {

case 0:
  lcd.print("Page1 Case0         ");
  if (press == 1) {
    press = 0;
  }
  break;
case 1:
  lcd.print("Page1 Case1         ");
  if (press == 1) {
    press = 0;
  }
  break;

case 2:
  lcd.print("Page1 Case2    exit ");
  if (press == 1) {
    press = 0;
    page = 0;
    poz = 0;
  }
  break;
}
}
//*************************************************Pages 2*****************************************
void page2() {
poz_min = 0;
poz_max = 2;
press_max = 1;

lcd.setCursor(0, 0);
lcd.print("Page2               ");
lcd.setCursor(0, 1);
switch (poz) {

case 0:
  lcd.print("Page2 Case0         ");
  if (press == 1) {
    press = 0;
  }
  break;
case 1:
  lcd.print("Page2 Case1         ");
  if (press == 1) {
    press = 0;
  }
  break;

case 2:
  lcd.print("Page2 Case2  exit   ");
  if (press == 1) {
    press = 0;
    page = 0;
    poz = 1;
  }
  break;
}
}
//*************************************************Pages 3*****************************************
void page3() {
poz_min = 0;
poz_max = 2;
press_max = 1;
lcd.setCursor(0, 0);
lcd.print("Page3               ");

switch (poz)
{
case 0:
  lcd.setCursor(0, 1);
  lcd.print("Page3 Case0         ");
  if (press == 1) {
    lcd.setCursor(0, 1);
    lcd.print("                    ");
    //navi();
  }
  break;

case 1:
  lcd.setCursor(0, 1);
  lcd.print("Page3 Case1         ");
  if (press == 1) {
    press = 0;
  }
  break;

case 2:
  lcd.setCursor(0, 1);
  lcd.print("Page3 Case2  exit   ");
  if (press == 1) {
    press = 0;
    page = 0;
    poz = 2;
  }
  break;
}
}
//*************************************************Pages 4*****************************************
void page4() {
poz_min = 0;
poz_max = 1;
press_max = 1;

lcd.setCursor(0, 0);
lcd.print("Page4               ");
lcd.setCursor(0, 1);
switch (poz) {

case 0:
  lcd.print("Page4 Case0  branch ");
  if (press == 1) {
    press = 0;
    page = 5;                                   //branches to page5() menu
    poz = 0;                                    //at position 0 on button 'S' press
    break;

  case 1:
    lcd.setCursor(0, 1);
    lcd.print("Page4 Case1  exit   ");
    if (press == 1) {
      press = 0;
      page = 0;
      poz = 3;
    }
    break;
  }
  }
}
//*************************************************Pages 5*****************************************
void page5() {
poz_min = 0;                      //see void MainmenuBtn()
poz_max = 1;                      //see void MainmenuBtn()
press_max = 1;                    //used when you have multiple selection within a section-increase number
                                  //see  original script for example
lcd.setCursor(0, 0);
lcd.print("Page5               ");
lcd.setCursor(0, 1);
switch (poz) {

case 0:
  lcd.print("Page5 Case0         ");
  break;

case 1:
  lcd.setCursor(0, 1);
  lcd.print("Page5 Case1  exit   ");
  if (press == 1) {                 //variable set to '1' when the 'S' key is pressed
    press = 0;
    page = 4;                         //this is the page() that you return to after the 'S' button is pressed
    poz = 1;                          //this is the 'case' number that you will return to for that page
  }
  break;
}
}

I have only inserted print statements where operational code can be placed, to keep it universally open. To reduce the size of the Global variables use the >>lcd.print(F("TEXT"));<< method, it works really well. Also works on Serial.print....Something for you to fiddle with.

I think that the reason why nobody tried this is that you did a huge work on your first example, so maybe someone (I admit, me too) postponed this because they had too few time at the moment. Anyway good job at actually writing a working version and thumbs up for your attitude. If your own answer successfully answers your question, mark it as accepted (when you can) so that everybody coming here will know that your code works

Thanks Mate...will do, but how do I mark as accepted???, never done it before.

What do you know, there is a HELP page up top...I have to wait 48 hours to accept...  ;-)   Update--have just about finished making a Menu with this and it is quite smooth once I got the hang of it..several levels deep. There actually is no practical limit to the depth. pleasantly surprised.

yes, you have to wait (that's to prevent some people from abusing this function to quickly gain reputation, I think). But.. Well, this is a perfectly legit case: you asked, nobody answered, you found a solution and shared it... Thank you for your effort :)

I am pretty new to all this but I cannot find a simple answer in your code. What pin numbers on the Arduino do I use to attach each button to? I am using standard everyday push buttons and a breadboard for this project. A0 is not enough for it to work. There has to be more to it. What am I missing?

Deve, you are not missing anything, it was exactly as you read it.  Since you are pretty new I would look at a straight forward keypad that consumes 8 pins if I was you.  If you are short of space you can always put that though a GPIO Expander that is controlled by I2C.

Deve this link should explain how to set up the buttons    http://forum.arduino.cc/index.php?topic=8558.0


text:
error: expected primary-expression before '(' token
I have a decent level of programming skill, or at least I thought so. I've been getting an error when compiling this Ardulno sketch. I don't really know what this error means or how to fix it. What's wrong with my code that's causing these errors. I was in the middle of making a big change to my code, so a lot of it is commented out because I haven't gotten to those parts.
code:
#include <LinkedList.h>

const uint8_t PinLeft = 2;
const uint8_t PinMiddle = 3;
const uint8_t PinRight = 4;
const uint8_t PinLED = 13;

enum MouseButtons {LEFT, MIDDLE, RIGHT} ;

bool leftPressed = false;
bool middlePressed = false;
bool rightPressed = false;

void sendMouseState() {
    if (leftPressed == true && middlePressed == false && rightPressed == false) {
        Mouse.set_buttons(1, 0, 0);
    } else if (leftPressed == true && middlePressed == true && rightPressed == false) {
        Mouse.set_buttons(1, 1, 0);
    } else if (leftPressed == true && middlePressed == true && rightPressed == true) {
        Mouse.set_buttons(1, 1, 1);
    } else if (leftPressed == true && middlePressed == false && rightPressed == true) {
        Mouse.set_buttons(1, 0, 1);
    } else if (leftPressed == false && middlePressed == true && rightPressed == false) {
        Mouse.set_buttons(0, 1, 0);
    } else if (leftPressed == false && middlePressed == false && rightPressed == true) {
        Mouse.set_buttons(0, 0, 1);
    } else if (leftPressed == false && middlePressed == true && rightPressed == true) {
        Mouse.set_buttons(0, 1, 1);
    } else if (leftPressed == false && middlePressed == false && rightPressed == false) {
        Mouse.set_buttons(0, 0, 0);
    }
}

void mouseButtonPress(MouseButtons theButton);
void mouseButtonPress(MouseButtons theButton) {
    if (theButton == MouseButtons::LEFT) {
        leftPressed = true;
    } else if(theButton == MouseButtons::MIDDLE) {
        middlePressed = true;
    } else if (theButton == MouseButtons::RIGHT) {
        rightPressed = true;
    }
}

void mouseButtonRelease(MouseButtons button);
void mouseButtonRelease(MouseButtons button) {
    if (button == LEFT) {
        leftPressed = false;
    } else if(button == MIDDLE) {
        middlePressed = false;
    } else if (button == RIGHT) {
        rightPressed = false;
    }
}

volatile unsigned int nextPressLeft = 0;
volatile unsigned int nextPressCenter = 0;
volatile unsigned int nextPressRight = 0;
const int timeBetween = 150; //milliseconds

enum ActionType {KB, MOU}; //keyboard or mouse

class Action {
    public:
        uint16_t keyCode;
        ActionType actionType;

        Action (uint16_t keyCode, ActionType actionType) {
            this->keyCode = keyCode;
            this->actionType = actionType;
        }

};

class ModeAction {

    public:
        LinkedList<Action> *keys = new LinkedList<Action>();

        void addAction(Action action) {
            keys->add(action);
        }

};

class ActionManager {

    private:
        uint8_t modeL = 1;
        uint8_t modeM = 1;
        uint8_t modeR = 1;

        LinkedList<ModeAction> *lActions = new LinkedList<ModeAction>();
        LinkedList<ModeAction> *mActions=new LinkedList<ModeAction>();
        LinkedList<ModeAction> *rActions=new LinkedList<ModeAction>();

        bool lActing = false, mActing = false, rActing = false;

    public:
        ActionManager() {
            //actions for left switch
            //mode 1
            lActions->add(ModeAction());
            lActions->get(lActions->size() - 1).addAction(Action(MouseButtons.LEFT, ActionType.MOU));
            //mode 2
            lActions->add(ModeAction());
            lActions->get(lActions->size() - 1).addAction(Action(KEY_F11, ActionType.KB));
            //mode 3
            lActions->add(ModeAction());
            lActions->get(lActions->size() - 1).addAction(Action(KEY_LEFT_CTRL, ActionType.KB));
            lActions->get(lActions->size() - 1).addAction(Action(KEY_LEFT_ALT, ActionType.KB));
            //mode 4
            lActions->add(ModeAction());
            lActions->get(lActions->size() - 1).addAction(Action(KEY_W, ActionType.KB));

            //actions for middle switch
            //mode 1
            mActions->add(ModeAction());
            mActions->get(lActions->size() - 1).addAction(Action(MouseButtons.MIDDLE, ActionType.MOU));

            //actions for right switch
            //mode 1
            rActions->add(ModeAction());
            rActions->get(lActions->size() - 1).addAction(Action(MouseButtons.RIGHT, ActionType.MOU));

        }

        void cycleModeL() {
            this->modeL++;
            if(this->modeL >= lActions->size()) {
                this->modeL = 1;
            }
        }

        void cycleModeM() {
            this->modeM++;
            if(this->modeM >= mActions->size()) {
                this->modeM = 1;
            }
        }

        void cycleModeR() {
            this->modeR++;
            if(this->modeR >= rActions->size()) {
                this->modeR = 1;
            }
        }

    private:

        //void doDownActions(ModeAction modeActions, uint8_t mode) {
            //for (int i = 0; i < modeActions.at(mode).keys.length(); i++) {
                //if (modeActions[mode][i].keys[i].actionType == ActionType.KB) {
                    //Keyboard.press(modeActions[mode].keys[i].keyCode)
                //} else if (modeActions[mode].keys[i].actionType == ActionType.MOU) {
                    //mouseButtonPress(modeActions[mode].keys[i].keyCode);
                //}
            //}
            //sendMouseState();
        //}
//
        //void doUpActions(ModeAction modeActions, uint8_t mode) {
            //for (int i = 0; i < modeActions[mode].keys.length(); i++) {
                //if (modeActions[mode][i].keys[i].actionType == ActionType.KB) {
                    //Keyboard.release(modeActions[mode].keys[i].keyCode)
                //} else if (modeActions[mode].keys[i].actionType == ActionType.MOU) {
                    //mouseButtonRelease(modeActions[mode].keys[i].keyCode);
                //}
            //}
            //sendMouseState();
        //}

    public:

        //void leftDown() {
            //if (lActing == false) {
                //lActing = true;
                //doDownActions(lActions, modeL);
            //}
        //}
//
        //void middleDown() {
            //if (mActing == false) {
                //mActing = true;
                //doDownActions(mActions, modeM);
            //}
        //}
//
        //void rightDown() {
            //if (rActing == false) {
                //rActing = true;
                //doDownActions(rActions, modeR);
            //}
        //}
//
        //void leftUp() {
            //if (lActing == true) {
                //lActing = false;
                //doUpActions(lActions, modeL);
            //}
        //}
//
        //void middleUp() {
            //if (mActing == true) {
                //mActing = false;
                //doUpActions(mActions, modeM);
            //}
        //}
//
        //void rightUp() {
            //if (rActing == true) {
                //rActing = false;
                //doUpActions(rActions, modeR);
            //}
        //}

};

ActionManager actionManager = ActionManager();

void setup() {

    Serial.begin(115200);

    pinMode(PinLED, OUTPUT);

    //pinMode(PinRight, INPUT_PULLUP); // sets the digital pin as output
    //attachInterrupt(PinRight, isrChangeR, CHANGE); // interrrupt is data ready
//
    //pinMode(PinMiddle, INPUT_PULLUP); // sets the digital pin as output
    //attachInterrupt(PinMiddle, isrChangeM, CHANGE); // interrrupt is data ready
//
    //pinMode(PinLeft, INPUT_PULLUP); // sets the digital pin as output
    //attachInterrupt(PinLeft, isrChangeL, CHANGE); // interrrupt is data ready

}

void loop() {

    //if (Serial.available()) {
////change mode
        //mode = Serial.parseInt();
//
////release all buttons
        //Keyboard.releaseAll();
        //Mouse.set_buttons(0, 0, 0);
//
////turn off LED
        //digitalWrite(PinLED, LOW);
//
////flush the serial input buffer
        //while (Serial.available()) {
            //Serial.read();
        //}
//
    //}
    //delay(1000);
    //Serial.println("Running");
}

//void isrChangeL() {
    //cli();
    //if (digitalRead(PinLeft) == LOW && nextPressLeft < millis()) {
////Serial.println("Pressed");
        //digitalWrite(PinLED, HIGH); //set the LED on
//
        //if (mode == 0) {
            //Mouse.set_buttons(1, 0, 0);
        //} else if (mode == 1) {
            //Keyboard.press(KEY_F11);
        //} else if (mode == 2) {
            //Keyboard.press(KEY_LEFT_CTRL);
            //Keyboard.press(KEY_LEFT_ALT);
        //} else if (mode == 3) {
            //Keyboard.press(KEY_W);
        //}
//
        //nextPressLeft = millis() + timeBetween;
//
    //} else {
//// Serial.println("Released");
        //digitalWrite(PinLED, LOW); // set the LED off
//
        //if (mode == 0) {
            //Mouse.set_buttons(0, 0, 0);
        //} else if (mode == 1) {
            //Keyboard.release(KEY_F11);
        //} else if (mode == 2) {
            //Keyboard.release(KEY_LEFT_CTRL);
            //Keyboard.release(KEY_LEFT_ALT);
        //} else if (mode == 3) {
            //Keyboard.release(KEY_W);
        //}
//
        //nextPressLeft = millis() + timeBetween * 0.6;
//
//
    //}
    //sei();
//}
//
//void isrChangeM() {
    //cli();
////if (digitalRead(PinMiddle) == LOW && nextPressCenter < millis())
////{
////Keyboard.press(KEY_SPACE);
////delay(250);
////Keyboard.release(KEY_SPACE);
////}
//
    //if (digitalRead(PinMiddle) == LOW && nextPressCenter < millis()) {
////Serial.println("Pressed");
        //digitalWrite(PinLED, HIGH); //set the LED on
////Mouse.set_buttons(0, 1, 0);
//
        //nextPressCenter = millis() + timeBetween;
//
    //} else {
//// Serial.println("Released");
        //digitalWrite(PinLED, LOW); // set the LED off
////Mouse.set_buttons(0, 0, 0);
//
        //nextPressCenter = millis() + timeBetween * 0.6;
//
//
    //}
//
    //sei();
//}
//
//void isrChangeR() {
    //cli();
    //if (digitalRead(PinRight) == LOW && nextPressRight < millis()) {
////Serial.println("Pressed");
        //digitalWrite(PinLED, HIGH); // set the LED on
        //Mouse.set_buttons(0, 0, 1);
////Keyboard.press(KEY_F11);
        //nextPressRight = millis() + timeBetween;
    //} else {
//// Serial.println("Released");
        //digitalWrite(PinLED, LOW); // set the LED off
        //Mouse.set_buttons(0, 0, 0);
////Keyboard.release(KEY_F11);
        //nextPressRight = millis() + timeBetween * 0.6;
    //}
    //sei();
//}

compiler log:
Compiling debug version of 'click_switch_5_cycling' for 'Teensy LC'
click_switch_5_cycling.ino: In constructor ActionManager::ActionManager()

click_switch_5_cycling.ino: 106:53: error: expected primary-expression before '(' token

click_switch_5_cycling.ino: 106:66: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 106:83: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 109:53: error: expected primary-expression before '(' token

click_switch_5_cycling.ino: 109:73: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 112:53: error: expected primary-expression before '(' token

click_switch_5_cycling.ino: 112:79: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 113:53: error: expected primary-expression before '(' token

click_switch_5_cycling.ino: 113:78: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 116:53: error: expected primary-expression before '(' token

click_switch_5_cycling.ino: 116:71: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 121:53: error: expected primary-expression before '(' token

click_switch_5_cycling.ino: 121:66: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 121:85: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 126:53: error: expected primary-expression before '(' token

click_switch_5_cycling.ino: 126:66: error: expected primary-expression before '.' token

click_switch_5_cycling.ino: 126:84: error: expected primary-expression before '.' token

click_switch_5_cycling.ino:1: In file included from
LinkedList.h: In instantiation of bool LinkedList<T>::add(T) [with T = Action]
click_switch_5_cycling.ino:83: required from here

LinkedList.h: 192:37: error: use of deleted function 'ListNode<Action>::ListNode()
ListNode<T> *tmp = new ListNode<T>()
LinkedList.h:19: note  ListNode<Action>  ListNode() is implicitly deleted because the default definition would be ill-formed
struct ListNode

LinkedList.h: 19:8: error: no matching function for call to 'Action::Action()
click_switch_5_cycling.ino:70: note  candidate  Action  Action(uint16_t, ActionType)
this->actionType = actionType
click_switch_5_cycling.ino:70: note    candidate expects 2 arguments, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(const Action&)
uint16_t keyCode
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(Action&&)
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided

click_switch_5_cycling.ino:1: In file included from
LinkedList.h: In instantiation of ListNode<T>* LinkedList<T>::getNode(int) [with T = ModeAction]
LinkedList.h:314: required from T LinkedList<T>  get(int) [with T = ModeAction]
click_switch_5_cycling.ino:106: required from here
LinkedList.h: 160:9: warning: converting 'false' to pointer type 'ListNode<ModeAction>*' [-Wconversion-null]
return false
LinkedList.h: In instantiation of bool LinkedList<T>::add(int, T) [with T = Action]
click_switch_5_cycling.ino:262: required from here

LinkedList.h: 177:37: error: use of deleted function 'ListNode<Action>::ListNode()
ListNode<T> *tmp = new ListNode<T>()
LinkedList.h: In instantiation of bool LinkedList<T>::unshift(T) [with T = Action]
click_switch_5_cycling.ino:262: required from here

LinkedList.h: 218:37: error: use of deleted function 'ListNode<Action>::ListNode()
ListNode<T> *tmp = new ListNode<T>()
LinkedList.h: In instantiation of T LinkedList<T>::remove(int) [with T = Action]
click_switch_5_cycling.ino:262: required from here

LinkedList.h: 290:12: error: no matching function for call to 'Action::Action()
return T()
click_switch_5_cycling.ino:70: note  candidate  Action  Action(uint16_t, ActionType)
this->actionType = actionType
click_switch_5_cycling.ino:70: note    candidate expects 2 arguments, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(const Action&)
uint16_t keyCode
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(Action&&)
Error compiling project sources
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided
Debug build failed for project 'click_switch_5_cycling'

click_switch_5_cycling.ino:1: In file included from
LinkedList.h: In instantiation of T LinkedList<T>::pop() [with T = Action]
click_switch_5_cycling.ino:262: required from here

LinkedList.h: 242:12: error: no matching function for call to 'Action::Action()
return T()
click_switch_5_cycling.ino:70: note  candidate  Action  Action(uint16_t, ActionType)
this->actionType = actionType
click_switch_5_cycling.ino:70: note    candidate expects 2 arguments, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(const Action&)
uint16_t keyCode
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(Action&&)
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided

click_switch_5_cycling.ino:1: In file included from
LinkedList.h: In instantiation of T LinkedList<T>::shift() [with T = Action]
click_switch_5_cycling.ino:262: required from here

LinkedList.h: 268:12: error: no matching function for call to 'Action::Action()
return T()
click_switch_5_cycling.ino:70: note  candidate  Action  Action(uint16_t, ActionType)
this->actionType = actionType
click_switch_5_cycling.ino:70: note    candidate expects 2 arguments, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(const Action&)
uint16_t keyCode
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(Action&&)
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided

click_switch_5_cycling.ino:1: In file included from
LinkedList.h: In instantiation of T LinkedList<T>::get(int) [with T = Action]
click_switch_5_cycling.ino:262: required from here

LinkedList.h: 316:14: error: no matching function for call to 'Action::Action()
T())
click_switch_5_cycling.ino:70: note  candidate  Action  Action(uint16_t, ActionType)
this->actionType = actionType
click_switch_5_cycling.ino:70: note    candidate expects 2 arguments, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(const Action&)
uint16_t keyCode
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided
click_switch_5_cycling.ino:65: note  candidate  constexpr Action  Action(Action&&)
click_switch_5_cycling.ino:65: note    candidate expects 1 argument, 0 provided

Thanks for any help you can give me about what these errors are and how to fix them.

You seem to have been programming in Java recently, because many of your errors have a Java ‘whiff’ to them. This, as you’ve tagged, is C++, not Java.

sendMouseState:
a. You wrote leftPressed == true. This is much more simply expressed by the expression leftPressed.
b. You wrote middlePressed == false. This is much more simply expressed using the “not” operator !, as in !middlePressed.
c. The code tests all eight possible combinations of leftPressed, middlePressed and rightPressed, calling Mouse.set_buttons(#,#,#);
However, bools evaluate to numbers: false evaluates to 0, while true evaluates to 1. All eight tests, and therefore the entire function, can therefore be boiled down to the single line:
Mouse.set_buttons(leftPressed, middlePressed, rightPressed);
You declared to the compiler, in a few places, “There’s going to be a function called (e.g) void mouseButtonPress(MouseButtons theButton);”
That’s fair enough - but the compiler only needs that if you’re going to call the function before you define it. Since you follow the declarations immediately by the definitions, the declarations are unnecessary: get rid of them.
Use of enums:
Declaring an enum lets you use symbols instead of raw numbers: well done! However, that’s all you need to use: the enum’s symbol: LEFT, MIDDLE or RIGHT is all you need.
If you do feel the need to express the enum’s name, you need to use the :: operator, not the . operator: MouseButtons::LEFT.
Use of new:
You do not need to call new to create members of classes. Well, OK, you might if they’re declared as pointers (which you have done), but that’s your problem: you should declare them as simple members, not pointer members.
For example, instead of:
LinkedList<Action> *keys = new LinkedList<Action>();

you simply need:
LinkedList<Action> keys;

Note that no new is needed now. Then, everywhere that you dereference the member with keys->add(action);, you use keys.add(action); instead.
Use of this->:
You use this-> a lot. You practically never have to: however, the one time you did need to was in the code:
Action (uint16_t keyCode, ActionType actionType) {
    this->keyCode = keyCode;
    this->actionType = actionType;
}

Here, this-> was needed to distinguish the class members from the passed-in parameters that have the same name. However, if you’d written the constructor correctly, using initialisation instead of assignment, you wouldn’t have needed this-> here either:
Action (uint16_t keyCode, ActionType actionType) :
    keyCode(keyCode),
    actionType(actionType) {
}

add() followed by get():
You use the following code:
lActions.add(ModeAction());
lActions.get(lActions->size() - 1).addAction(Action(LEFT,MOU));

That is, you add an empty ModeAction, then fetch it back with get(...) before manipulating it. Don’t.
Instead, create a temporary ModeAction object, get it ready, then add() it to the list:
ModeAction lMode1;
lMode1.addAction(Action(LEFT,MOU));
lActions.add(lMode1);

1a and 1b are bad practice in Java too, 1c and 6 are bad algorithm (n Java too)

Dart, actually - been trying to learn it. Thanks for your detailed response.

a,b. I'm working with other people who aren't really programmers so I wanted to keep it explicit.
c. That's a good point, thanks.
I did that because I was getting the error: "variable or field 'mouseButtonPress' declared void" and I read that that was how to fix it. Something about the way Arduino handles function definitions.
I want the code to be explicit, so I'll change those to :: .

I was using example code given by the LinkedList library (https://github.com/ivanseidel/LinkedList).
Ok.
Ok, I changed those.

I think I made all the changes you suggested, but it still won't compile. Here's the new code https://gist.github.com/dude8604/98f7d8e7e6f4d74349b1b974e8ea0d17 and compiler log https://gist.github.com/dude8604/e9685c4b49b6c90922ad09a69b5e4c34
It seems like most of the errors point to the LinkedList library. Are the remaining errors with the library or my code? Thanks.

@dude8604 4. That example LinkedList code is... abbreviated. It starts simply enough with a normal variable, then talks about creating one with new. It wasn't implying that was how it had to be done... It's also got a bug in it: I'll send a Pull request to the author. Edit: No need - it's already there, just not actioned. Sigh!

@dude8604  Since you want to create a linked list of Actions, in your Action class you need to have a "default" constructor: one which takes zero parameters. If you add the line
"Action () : keyCode(0), actionType(KB) {}"
to the class, LinkedList<Action> will now compile.

The compiler is giving you a clue that the problem is around line 106. You have there:
  LinkedList<ModeAction> *lActions = new LinkedList<ModeAction>();
  LinkedList<ModeAction> *mActions=new LinkedList<ModeAction>();
  LinkedList<ModeAction> *rActions=new LinkedList<ModeAction>();

You can't do procedural code (like new) in a data declaration. Also, I doubt that there is a function to be called so I would get rid of the brackets. Initializing member fields should be done in the constructor, not in the declaration.

I moved the assignment part into the constructor but I'm still getting similar errors. Should I edit my code and compiler log in the original post?

should not be a problem with C++11 https://en.cppreference.com/w/cpp/language/data_members

This isn't a forum, so to-ing and fro-ing with changes to the original post makes the question a moving target, and then the answers look meaningless. Hopefully John Burger's rather comprehensive answer will help you without you having to do that.

Juraj is right however that declaring pointers like that is OK under C++11. However as John Burger points out, it is easier not to use pointers in the first place. For one thing, if you are going to use new then you should use delete in the destructor.

you use wrong syntax to access an enum member. use :: not .
Action(MouseButtons::LEFT, ActionType::MOU)
EDIT:
second error is that LinkedList requires constructor without parameters on the template type
add constructor without parameters to class Action

Re: second error, Is there another Arduino vector library that wouldn't require that?

I tried it and now the program freezes.

why do you want to use dynamic vector? use array

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
ATtiny85 MIDI IN using SoftwareSerial - Is it possible?
I'm trying to read MIDI notes using an ATtiny85 via SoftwareSerial; so far, I've got no success at all.

The ATtiny is using the internal clock, 8Mhz, 5V.
The MIDI keyboard sends clean note on/off messages (tested with a MIDI monitor).
I've tried several test programs, particularly Nick Gammon's, as described here.
I've followed Nick's schematics to build the connector, and I can confirm his program works with an Arduino, but not with the ATtiny.
I calibrated the Tiny with OSCCAL - still no luck.
As far as I can tell, midiSerial.available() is always 0, in every program I've tried.
SoftwareSerial works fine for the purpose of MIDI out.

That's as far as I've got. I'd appreciate any pointers, especially if anyone else could try Nick's code and see if it works.
EDIT
There was an issue with my local version of SoftwareSerial. I had commented out code so that I could use pin change interrupts in my MIDI out program, but those interrupts are essential for MIDI input. Once I uncommented the code, all the programs I tested worked, so it is indeed possible to receive MIDI using an ATtiny.
That said, I've tried four keyboards as inputs and only one has worked so far, a Korg 01/W proX. The same happens when I load the MIDI code directly in the Arduino, so based on the answers below I will try a different optocoupler, and post my results here for the sake of improving on the answer.
Here's the schematics I was talking about:

The schematic is wrong: pin 2 at the receiver must not be connected to ground, and the optocoupler is not reliable at MIDI speeds. See 4N35 opto-isolator for MIDI input does not work?

true- I've just added the schematic above. The code is relevant because the author claims it's been tested, but it's one of several I've tried with identical results, so I don't think it is as central to the question.

Your link now points to a better schematic …

@LookAlterno there's no double jump - scroll down to "Example code for ATtiny85"

You might try NeoSWSerial.  It has a configuration option to avoid the PCI vector problem, and it now supports the MIDI baud rate.  It is MUCH more efficient than SoftwareSerial.

I'd also say it's the opto isolator. I am getting good results with a 6N138. I also had good results with a 6N137 but based on reports from other people it seems that it can fail with certain devices.

@CL fixed up the earth pin on the schematic.

I have done tests with a normal Arduino with software serial and missed quite a bit of messages, so I would advice to use hardware serial's instead.
For MIDI Out probably it works, but for MIDI In I have bad experiences. Especially when it comes to many messages, like aftertouch/pitch bend etc.
Also, I tried some optocouplers which didn't work well (like 6N137). I now use H11L1 optocouplers (they are white compared to most black ICs) and work perfectly.
You already checked the clean note on/note off ... are you sure it doesn't send active messages?
Below the schematic as I use it.. It does not matter if an STM32 or Arduino is used. Actually I haven't checked if H11L1 are 3.3V or 5V but they seem to work on both.

simulate this circuit – Schematic created using CircuitLab

Yes, no other messages at all.

From yours and CLs comment it looks like I can't rely on the 435, so I'll try the H11L1.

It might be that different resistor values should be used, if you want I can check when I'm home this evening.

I'd be very grateful if you could :)

I added my circuit (hopefully without mistakes)

That looks great, I'll order the parts and report back asap!

Good luck .. btw I tried it earlier with an Arduino Uno/Mega (5V) and today with a STM32 (3.3V). ... both work. Btw, there is no difference between H11L1 and H11L1M except the manufacturer (some are white, some are black).

The pin numbers and several connections are wrong.

@CL I checked it and the only mistake I could find was the connection with the wire left of R2. I'm really interested what pin numbers/connections are wrong, because it is according to the circuit I built (on a breadboard).

DIN connector number the pins differently. R4 must be a pullup on the output signal. (And this schematic would be much more readable if you didn't try to connect all VCC and GND signals together; see, e.g., this page.)

@CL Thank you for the comments ... true, I numbered the DIN pins myself (I will follow the original numbering, but get always confused about the side to look at). And a good tip about the VCC/GND ... I really used the pullup the way in the schematics and works, but I will check the official one and change mycircuit accordingly.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
ATtiny85 plugin and removed it self
So I bought ATtiny85 recently, when I plug it to my PC it make sound like mouse has been plugin, but then it make sound like the device has been removed. It happen again and again until I remove the device. Is it the device problem or am I missing something? Can I fix it?

Please give more details about the exact board you have, any other observations (led lighting up on the board or not), if you've tried plugging it into another port or via a hub etc.

The Uno does not have an AtTiny85 processor so I will remove that tag.

The AtTiny85 is a processor and not a board. It always helps to give more details. A link to the exact board you bought would be helpful.

I'm assuming you've bought a Digispark (or compatible) ATTiny85 USB board.
The sound of a USB device inserting and removing is normal. When the digiSpark boots it listens to the USB bus for a short period so you can upload your sketches. Then it proceeds to boot your sketch.
If no sketch has been uploaded, it might just reboot until you upload one. The Digisparks I have, have all had a "blink" sketch preloaded but yours may not.
The "problem" will go away when you start running your own sketches. It will then only announce itself once and then remove itself from the USB bus, unless your sketch also communicates via the USB bus.


text:
What is wrong with my code? Did you forget '()'?
#include <SimbleeBLE.h>

// constants won't change. They're used here to set pin numbers:

const int ButtonPlayPause = 15;
const int ButtonNext = 12;
const int ButtonPrevious = 11;
const int OBled = 29;
       int Playp = 1;

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup()
{

  pinMode(ButtonPlayPause, INPUT);
  pinMode(ButtonNext, INPUT);
  pinMode(ButtonPrevious, INPUT);

  pinMode(OBled, INPUT);

  SimbleeBLE.deviceName = "GBAND";

  Serial.begin(115200);

  SimbleeBLE.begin();

  SimbleeBLE.txPowerLevel = +4;
}

void loop()
{
  buttonState = digitalRead(ButtonPlayPause);
  if (buttonState == HIGH)
  {
    SimbleeBLE.begin();
    SimbleeBLE.deviceName = "GBAND";
    //More code here to establish connection with android
     SimbleeBLE.sendInt = (Playp);
    digitalWrite(OBled, HIGH);
    SimbleeBLE.end();
    digitalWrite(OBled, LOW);
  } else  {
            buttonState = digitalRead(ButtonNext);
            if (buttonState == HIGH)
            {
              SimbleeBLE.begin();

              //More code here to establish connection with android

              digitalWrite(OBled, HIGH);
              SimbleeBLE.end();
              digitalWrite(OBled, LOW);
            } else  {
                      buttonState = digitalRead(ButtonPrevious);
                      if (buttonState == HIGH)
                      {
                        SimbleeBLE.begin();
                        //More code here to establish connection with android

                        digitalWrite(OBled, HIGH);
                        SimbleeBLE.end();
                        digitalWrite(OBled, LOW);
                      }
                    }
          }
    }

This is the error I keep getting:
Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Simblee"

C:\Users\Lestat\Desktop\SD PROJECR PAPERWORK\Sketch programs\sketch_mar20a\sketch_mar20a.ino: In function 'void loop()':

sketch_mar20a:42: error: invalid use of member function (did you forget the '()' ?)

     SimbleeBLE.sendInt = (Playp);
                        ^
exit status 1
invalid use of member function (did you forget the '()' ?)

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Tagging a question [tag:compilation-errors] and then not posting them is the fast track to getting ignored.

Also asked at: http://forum.arduino.cc/index.php?topic=536567 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

You're trying to assign a value to a function. That is almost certainly wrong.
SimbleeBLE.sendInt(Playp);

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Getting random values on Arduino Duemilanove 328
I am using Arduino Duemilanove 328,and running the AnalogReadSerial example sketch.
Even when nothing is connected to the Arduino board it still shows a value of about 350 out of 1023. Ideally it should have shown 0 out of 1023 when nothing is connected to Arduino.
So how can I solve this problem?

Connect it to something. E.g. a pull-down resistor if you want to read zero when nothing else is connected.

Why do you think it should show 0 when not connected to anything?
Does the antenna of your radio give a zero signal just because the end isn't connected to anything?  An Arduino's input pin (either analog or digital) is just the same.  If it isn't connected to anything then it just picks up noise - be that radio transmissions, induction from nearby mains wiring, neutrinos from Alpha Centauri...  Basically if it's not connected to anything then there is no way you can possibly know what the value should be since there is no set value.
In order to read 0 on the ADC the ADC has to be connected 0V.  That means connect it to ground.


text:
Power Arduino from 230v with battery fallback
I've build a fairly simple doorbell using Arduino Pro Mini 3.3V: https://www.youtube.com/watch?v=WFd94CYT2Lw&feature=youtu.be
Here's the current setup:

Arduino running off the 9 V battery
A simple speaker is connected to Arduino (powered from the battery, Arduino just drives it through a transistor)
Arduino is reading light level from the light meter every 200 ms.
Bulb is connected to the wire that is lit up when someone presses the doorbell button.

It works well - someone presses the doorbell button, bulb gets lit up, Arduino notices that (using light meter) and doorbell rings.
Problem
In short - battery life. This kind of setup lasts around 2-3 days off a single battery. I was reading all about how to run Arduino off a single battery for a few weeks, even months, but I'm not sure it's feasible in my case. First of all, I need to wake up Arduino every 100-200, maybe 500 milliseconds, to read the light level. Plus, many of those long-battery-life solutions involved basically building own Arduino-compatible scheme from scratch, which I'd like to avoid.
Idea
But... I have a 230 V power source - the one that drives the bulb. Issue is that this power source is down all the time, unless someone is pressing the doorbell button.
I could approach it in two ways:

When someone presses the button, I'd power the Arduino and immediately play a song. Issue with that approach is that if someone presses the button for just a split second, my Arduino would be powered up for just that short amount of time, and I wouldn't have enough time to play the complete song.
If I could possibly reverse the way doorbell button works, I could have +230V all the time, and 0 when someone presses the button. This way Arduino would be on all the time, and it would "notice" someone pressed the button when power would go down. Issue with that approach is that song would be played only once guest would release the doorbell button, + the time it takes for an Arduino to boot.

In both #1 and #2, I need two things then:
a) have Arduino on all the time, regardless of whether button is pressed or not
b) power Arduino from the doorbell to avoid having to use a battery
Which kind of means that I need to power Arduino from a dual source - 230 V and rechargeable battery. 230 V when available, and battery when 230 V goes down. In a perfect scenario, this battery would be charged from 230 V source too :)
Any ideas how to built such a thing? Is there some AC power module that I could use? How would I wire things up in such a case - Arduino, AC power module, rechargeable battery?
Or maybe I'm missing some easier, simpler solution here?

This kind of setup lasts around 2-3 days off a single battery.

I measured 15.8 mA consumption on my Pro Mini, running from 9V. A typical 9V battery may have a capacity of 500 mAh, so that is 500 / 15.8 = 31.6 hours. Thus your observed consumption is about right.
Probably 10 mA of that is the LED, so removing it would help. I have a page about power saving. You would want to investigate going into sleep mode, and waking long enough to check the light. You might be able to arrange a LDR in such a way that it generates an interrupt and wakes the processor immediately from a deep sleep.

Example of waking using an LDR
I made up a test like this:

D2 is one of the external interrupt pins so we can write a simple low-power sketch that sleeps all the time until the LDR gets enough light that the resistance drops, and D2 goes HIGH.
#include <avr/sleep.h>

const byte LED = 9;

void wake ()
{
  // cancel sleep as a precaution
  sleep_disable();
  // precautionary while we do other stuff
  detachInterrupt (0);
}  // end of wake

void setup ()
  {
  }  // end of setup

void loop ()
{

  // flash LED 5 times
  for (byte i = 0; i < 5; i++)
    {
    pinMode (LED, OUTPUT);
    digitalWrite (LED, HIGH);
    delay (100);
    digitalWrite (LED, LOW);
    delay (100);
    }

  pinMode (LED, INPUT);

  // disable ADC
  ADCSRA = 0;

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  sleep_enable();

  // Do not interrupt before we go to sleep, or the
  // ISR will detach interrupts and we won't wake.
  noInterrupts ();

  // will be called when pin D2 goes high
  attachInterrupt (0, wake, RISING);
  EIFR = bit (INTF0);  // clear flag for interrupt 0

  // turn off brown-out enable in software
  // BODS must be set to one and BODSE must be set to zero within four clock cycles
  MCUCR = bit (BODS) | bit (BODSE);
  // The BODS bit is automatically cleared after three clock cycles
  MCUCR = bit (BODS);

  // We are guaranteed that the sleep_cpu call will be done
  // as the processor executes the next instruction after
  // interrupts are turned on.
  interrupts ();  // one cycle
  sleep_cpu ();   // one cycle

  } // end of loop

My example just flashes an LED on pin 9 five times, that is where you can play your doorbell sound. Now, with no major external circuitry (like LEDs that are always on) it should have low power consumption.

What would be a good replacement for it, with low power draw and support for interrupts?

The LDR as described above. I measured 3 µA through the LDR when it was partly covered with a black box (my glasses case) and the room lights off. However it was daylight. I think that is pretty acceptable.

Come to think of it, you could probably turn this into a nice "doorway detector" (like they have in shops where it plays a sound when you break a light beam at the doorway). By arranging the LDR in a tube at one side of the door, and shining a light across the doorway into it (and probably tweaking the resistor values a bit) it would play a sound once you cross the beam.

Thanks! So if I'd remove the LED, I'd prolong battery life up to ~500 / (15.8 - 10) =~ 3.5 days. That's fine, but the big savings would be if my light meter supported interrupts, Unfortunately, BH1750 I use doesn't - no mention of "interrupts" here. What would be a good replacement for it, with low power draw and support for interrupts? I don't need a big resolution, light meter and a bulb are going to be in a box, so it'd be very dark inside when bulb is off. Also, do you have any pointers for the powering Arduino from a AC + battery?

See amended reply.

That's interesting. If I'd follow instructions here and disabled built-in LED, and then followed your sketch, by using a single 500mAh battery I could get 500mAh / (0.0541mA+0.003mA) / 24h =~ 365 days. And I even could use couple of AA batteries to go beyond that. Obviously minus speaker power consumption. Let's try that, but first I need to practice using multimeter to actually measure this stuff, and order LDR. Many thanks!

You can run a Pro-Mini just fine of a battery. It's the UNOs that cause a lot of problems, because of the onboard USB-to-Serial chip. The only thing you might want to tweak on this board, is removing the power-led, which I've recently done with a knife.
I poll the reflectivity of my power-meter every 250ms, and I'm getting at least 3 months of battery life out of 2 AA-batteries.
Depending on the light sensor you are using, you could even use interrupts to wake up the Arduino when the light is on, instead of having to poll every few milliseconds.

Thanks! I read about removing this LED. I'm surprised you get as much as 3 months of life with polling every 250ms. Maybe my speaker draws some power then, when off? I connected it to one of the outputs via small resistor and a NPN transistor. Collector and emitter are connected to battery VCC and GND. It's a simplest, 8 Ohm, 1 Watt speaker. I also used different battery, the 9V rectangular one. And I'm getting 2-3 days, measured on a brand new battery.

Do you put the arduino into sleepmode? Not just using delay.

I think so. I used "Low Power" library - here's the relevant line in my code: https://github.com/kamituel/arduino/blob/master/src/doorbell/rtttl_bin/rtttl_bin.ino#L43

The BH1750 takes around 16ms to do a measurement, so you are are already spending 15% of the time awake. I'd suggest just using a simple LDR (light dependent resistor) instead. They are only a few cents, and will be more than adequate in this case. Do you have a multi-meter, so you can measure the (average) current consumption? Low power can be hard to figure out sometimes. There's a lot of variables.

I did just borrow one, but it has quite big "plugs" so it's hard to connect it to the breadboard, so I wasn't able to measure anything meaningful. It's not "arduino-specific" multimeter,  rather one that can be used in more electric application. Can you recommend one that would be more convienient to use, would be sensitive enough to cover this kind of applications, and also not overly expensive? :)

Those "plugs" are standard on multimeters. There aren't any "arduino specific" multimeters. Any simple multimeter will be fine for a beginner. I got mine for 20 euro at a local hardware store. Not the best, but fine for basic usage. You want to measure the current used, so you put the meter into mA mode. Just place two wires with one side into the breadboard, the other two ends of the wires, you can just press against the two "plugs" with your fingers.

If you make it so that the light only goes out when you press the button, and connect a battery charger with that bulb in parallel, put a battery in the charger and plug the arduino into the battery, then use the light sensor approach to detect the button press and play a tune, it would work just fine... Really the only 3 things you might wanna worry about are the user holding the button for a few hours (which is very unlikely), power outages (can be solved using a UPS), and replacing the battery/bulb once every few years, depending on how good it is... Probably the simplest approach, not sure if it is the best tho...
But why not just plug the arduino to a phone charger that is then connected to the wall, and then use the doorbell switch as input for the arduino?

A small solar cell would not require excitation and would probably generate enough voltage to trigger an interrupt pin and wake up the MCU.


text:
How do you extend the wires from the arduino board to both fsr sensors to be placed on both chairs (one for each)
I’m trying to figure out how to extend the wires for both force sensitive resistors so that it could be place on each chair, one sensor on one chair and the other sensor on the other chair
This is how this was originally connected

So what would be the best way to extend both cables to place both sensors on each chair

why can't you use longer wires? Are there capacitance or noise problems?

In ADC sampling there will always be noise.  Longer cables may increase that noise.  Sensors with lower resistance tend have less noise.  For these reasons it would be better to start from a schematic, part numbers and / or specifications rather than a picture.
There are a number of ways to reduce noise.  Hardware solutions include twisted pair and shielded cables.  Software solutions include averaging multiple samples and removing outliers.
If all you are asking is if you can use longer cables, the answer is yes as long as you can tolerate the or compensate for additional noise if any.

In order to extend the wires you will need:

Crimp Connector Housing
Female Crimp Pins
Male Crimp Pins
Stranded Wire: 30 AWG

and if you want to do a better job than bread board then you can use a Strip board to solder your resistors on and some headers to connect your wires.
You should not get any noise in ideal situation.
I don't know where you from so I just posted the links to the store I usually buy from. you can find these items on ebay or similar. Plus you will need a crimping tool as well.


text:
Shift register 1's and 0's array to 4 int's function not working
I'm not sure if i should post this here or on StackOverflow but I am coding for an LED cube controlled with 4 shift registers. I have a function in a .h file that is supposed to take an array of 1s and 0s (to represent each LED) and then use the shiftOut function to shift the data into the shift registers. This is complicated that the shiftOut function has to take a int which it shifts out in binary and only goes 8 bits at a time. This means I have to separate my array into 4 groups of 8 and then convert each group into an int. I have tried to make my function do that but it is compiling fine and then not lighting up any LEDs. I believe the problem has to do with the way I'm separating the array into 4 smaller arrays althoughI can not figure out exactly what is going wrong, here is my code.
Main program:
#include <LEDcube.h>

int data = 2;
int clock = 3;
int latch = 4;

void setup()
{
  pinMode(data, OUTPUT);
  pinMode(clock, OUTPUT);
  pinMode(latch, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  int layer[32] = {0,

                  1,1,1,1,1,
                  0,0,0,0,0,
                  1,1,1,1,1,
                  0,0,0,0,0,
                  1,1,1,1,1,

                  0,0,0,0,0,0};
  write(data, clock, latch, layer);
}

LEDcube.h:
#include "Arduino.h"

int binToNum(int bin[])
{
  int j = 1;
  int num = 0;
  for(int i = 0; i < 8; i++, j = j * 2)
  {
    if(bin[i] == 1)
    {
      num = num + j;
    }
  }
  return num;
}
void write(int data, int clock, int latch, int layer[])
{
  int reg1[8];
  int reg2[8];
  int reg3[8];
  int reg4[8];
  for(int i = 0; 1 < 8; i++)
  {
    reg1[i] = layer[i];
  }
    for(int i = 0; 1 < 8; i++)
  {
    int q = i + 8;
    reg2[i] = layer[q];
  }
  for(int i = 0; 1 < 8; i++)
  {
    int q = i + 16;
    reg3[i] = layer[q];
  }
  for(int i = 0; 1 < 8; i++)
  {
    int q = i + 24;
    reg4[i] = layer[q];
  }
  int regnum1 = binToNum(reg1);
  int regnum2 = binToNum(reg2);
  int regnum3 = binToNum(reg3);
  int regnum4 = binToNum(reg4);
  digitalWrite(latch, LOW);
  shiftOut(data, clock, MSBFIRST, regnum4);
  shiftOut(data, clock, MSBFIRST, regnum3);
  shiftOut(data, clock, MSBFIRST, regnum2);
  shiftOut(data, clock, MSBFIRST, regnum1);
  digitalWrite(latch, HIGH);
}

for(int i = 0; 1 < 8; i++) is this correct? should it be for(int i = 0; i < 8; i++)?

I'm not sure what you mean @PhillyNJ

What are you using for a shift register?

@PhillyNJ means 1<8 instead of i<8 (notice the 1 (one) instead of the i (letter I))

ohhhhhhhhhhhhhhh, that typo might have been the problem

As noted in Stu's answer, the question's code does not pack bits properly into the bytes that shiftOut() will unpack them from.
If you merely want to make things work, as opposed to packing stuff up one place so it can be unpacked another, just write the bits to your SR yourself.  For example:
for (int i=0; i<32; ++i) {
  digitalWrite(data, layer[i]); // Put a bit on the data pin
  digitalWrite(clock, HIGH); // Pulse the clock
  digitalWrite(clock, LOW);
}
digitalWrite(latch, HIGH); // Pulse the latch
digitalWrite(latch, LOW);

If the clock or latch need low-going instead of high-going pulses, reverse the order of writing HIGH and LOW.

The problem is you need to write your data with all of your bits consolidated into a single integer instead of as an array of integers. For example, if you were to shiftOut(data, clock, MSBFIRST, 1) that would send 00000001, not 1. So for example, if you want to send out 1,0,1,0,1,0,1,0 you need to send shiftOut(data, clock, MSBFIRST, 170), because 170 in binary is 10101010. So you will need to figure out how to represent your data as an integer rather than array of integers of which you are only using the first bit.
EDIT:
I see that you are attempting to do a binary conversion, but your for loop is a little off. Try this instead:
for(int i = 0; i < 8; i++)
{
  if(bin[i] == 1)
  {
    num = num + j;
  }
  j = j * 2;
}

Even if that fixes it, you will probably still need to some major refactoring to get decent speed, currently you are using 128 bytes of memory to represent 4 bytes worth of data. and there are plenty of other little inefficiencies here and there.
EDIT 2:
The simplest version of the above functionality is this:
int data = 2;
int clock = 3;
int latch = 4;

void setup()
{
  pinMode(data, OUTPUT);
  pinMode(clock, OUTPUT);
  pinMode(latch, OUTPUT);
}

void loop()
{
  int data1 = 0b1111100000111110; //Set a variable using a binary constant
  int data2 = 0b0000111110000000;
  digitalWrite(latch, LOW);
  shiftOut(data, clock, MSBFIRST, data1);
  shiftOut(data, clock, MSBFIRST, data2);
  digitalWrite(latch, HIGH);
}

If you are going to be doing more bit level manipulation, you should probably learn various bit wise operators such as <<, >> &, ^, |, ~, &=, and |=. The Arduino documentation goes over them and what they do (scroll down, on the left under Bitwise Operators).

Thats what I was trying to do by converting my array of ones and zeros into an integer ( int regnum1 = binToNum(reg1); ) @Jake C

Thanks for the help although I don't think that the problem is in the binary to integer conversation function as it was works fine with out when called out side of the write function. I think the problem has more to do with separating the 32-bit array into 4 8-bit arrays, I should have made that clearer in the question. You do make a good point with the efficiency though and if you have any suggestions as to how I could improve that would be great.


text:
GPS very short distance calculation
I'm currently working on a project involving making a "parent-child distance warning system" with my Flora board + Ultimate GPS Module (https://www.adafruit.com/product/1059).
I'm on the preliminary phase and just trying to retrieve the current GPS module position, comparing it with a pre-fixed position (expressed in GPS decimal coordinates, e.g. 40.779006, -74.289395), calculate the distance between these two points and, if the distance is more than a certain value, say 20 meters, print on serial monitor a warning message.
I was able to correctly retrieve the GPS module position (expressed in decimal coordinates, as above), but when I try to calculate the distance I'm not able to achieve a few-meter accurancy.
So, my questions are:

Is there a specific/best formula to calculate short distances (max 100 meters) on the earth surface with an accurancy of 2-3 meters?
I tried with Haversine formula with not so bad results, but because of the scarce Double precision (in ATMega processors is the same of the Float one, i.e. 32 bits), I'm able to obtain a precision of only 6-7 digits in total (as stated in https://www.arduino.cc/en/Reference/Float). These approximations lead to large errors in the final distance value.
How can I obtain a fast and precise position update during my path?
If I walk along a direction I'm no able to retrieve a fast enough position update in terms of lat/lon coordinates.

Hope to be as much clear as possible and to have explained my problem, thanks in advance to anyone will give me any feedback or any information and please be patience for my bad english.
Filippo
[UPDATE]
@EdgarBonet that's exactly what I was looking for!!! Huge thanks!
Does the simple GPS library you linked is good to me also if my Flora board mounts an AtMega32u4 processor instead of the ATtiny85 you mentioned?
Last question: do you know how faster can I retrieve a GPS fix? I mean, if I am in a certain position (say X) and I am able to correctly obtain my GPS coordinates, then I move 5 meters ahead (say X+5), when I arrive at X+5 position can I retrieve within few seconds the X+5 GPS coordinates?
Thank you so much again @EdgarBonet!!
I'm currently working on a project involving making a "parent-child distance warning system" with my Flora board + Ultimate GPS Module (https://www.adafruit.com/product/1059).
I'm on the preliminary phase and just trying to retrieve the current GPS module position, comparing it with a pre-fixed position (expressed in GPS decimal coordinates, e.g. 40.779006, -74.289395), calculate the distance between these two points and, if the distance is more than a certain value, say 20 meters, print on serial monitor a warning message.
I was able to correctly retrieve the GPS module position (expressed in decimal coordinates, as above), but when I try to calculate the distance I'm not able to achieve a few-meter accurancy.
So, my questions are:

Is there a specific/best formula to calculate short distances (max 100 meters) on the earth surface with an accurancy of 2-3 meters?
I tried with Haversine formula with not so bad results, but because of the scarce Double precision (in ATMega processors is the same of the Float one, i.e. 32 bits), I'm able to obtain a precision of only 6-7 digits in total (as stated in https://www.arduino.cc/en/Reference/Float). These approximations lead to large errors in the final distance value.
How can I obtain a fast and precise position update during my path?
If I walk along a direction I'm no able to retrieve a fast enough position update in terms of lat/lon coordinates.

Hope to be as much clear as possible and to have explained my problem, thanks in advance to anyone will give me any feedback or any information and please be patience for my bad english.
Filippo
[UPDATE]
@EdgarBonet that's exactly what I was looking for!!! Huge thanks!
Does the simple GPS library you linked is good to me also if my Flora board mounts an AtMega32u4 processor instead of the ATtiny85 you mentioned?
Last question: do you know how faster can I retrieve a GPS fix? I mean, if I am in a certain position (say X) and I am able to correctly obtain my GPS coordinates, then I move 5 meters ahead (say X+5), when I arrive at X+5 position can I retrieve within few seconds the X+5 GPS coordinates?
Thank you so much again @EdgarBonet!!
[UPDATE 2]
The DistanceBetween method recommended to me by @EdgarBonet returns to me always 0, even if I move my self a couple of tens of meters.
But, maybe I am wrong in passing the parameters. Do I have to pass the lat/lon parameters as decimal coordinates (e.g: 45.892829, 12.082583)? If I am wrong, in which format do I have to pass the lat/lon parameters to the DistanceBetween method?

It may be that you cannot get this kind of accuracy with the position fix outputs of everyday GPS units, but rather that you need DGPS (or yet fancier schemes) capable units that can exchange their raw data readings to factor out the part of the inherent system error that is essentially the same in the local region, leaving only the position difference.  This is really a differential GPS question, not an Arduino question - or at least, don't try to do it on an Arduino until you've verified elsewhere that computations on real sample data yield a useful result.

Why not use a short range radio signal, i.e. Bluetooth.  Pair the parent and child and then pulse a signal between them.  As soon as a number of pulses are missed raise the alarm at the parent end.  Its a bit more clumsy if you have 5 children, but...

You will have trouble getting the accuracy you want. An SBAS enabled GPS will give you a position error of around 1 m under ideal conditions (and assuming you have SBAS coverage). Under poor conditions (non-ideal antenna location, lots of buildings/trees around etc...) then expect 5 m of error. That's for each device so double it for position differences.

@Filippo not related to athe question itself, but.. Please avoid using multiple accounts (partcularly to add information about the question, like you did in the pending edit)..

@CodeGorilla That tells you they have wandered off but it doesn't tell you which direction they went. It will also be very environment specific, lots of people around will absorb the signals and so shorten the range. Not necessarily a bad thing for this application but it wouldn't be a controllable effect.

Do you have two user accounts? You appear to be suggesting edits from an  account that differs from the account that you originally posted your question from. If you contact the moderators, then they can merge the two accounts for you.

@FilippoDamuzzo Re Update 2. As indicated in the linked page These routines work in units of 1e-4 arc minutes. Thus one degree is represented as 600,000 units They do this so that all of the calculations are done as integers which is then a lot faster. So if you have lat and lon in degrees then multiply them by the constant DEGREE to get the correct results.

The Haversine formula is way overkill for your needs. At the scale you
are concerned about, the Earth is essentially flat, so the distance
between two points is given by the standard Cartesian formula:
d = √(Δx2 + Δy2)
where Δx and Δy are the distances along the west–east and south–north
axes respectively. These can be computed from the differences in
latitude and longitude as
Δx = R Δλ cos(φ)
Δy = R Δφ
where φ is the latitude, λ is the longitude (both in radians), and R is
the Earth radius. The term cos(φ) accounts for the fact that, far from
the equator, consecutive meridians are closer together than consecutive
parallels. When computing this cosine, it does not matter whether you
use the latitude of either point.
I suggest you take a look at this simple GPS library. It was
designed for doing exactly this kind of simple calculations on a small
AVR processor like the ATtiny85. It should work great on your Flora. The
function you want is DistanceBetween(). It uses the “locally flat
Earth” approximation above, which is only good for distances up to a few
hundred kilometers.
A couple of things worth noting about this library:

the library trades accuracy for efficiency: everything is fixed-point
and it uses low-order polynomial approximations for cos(x) and
√(x2 + y2)
angles are given in units of 10−4 arc minutes, as this is
what you usually get from an NMEA sentence
DistanceBetween() reports the distance as an integer number of
meters, but you can easily modify it to give it in units of
half-meters, quarter-meters, etc.: just replace the value 512 in the
last line (return ... / 512;) by a smaller power of two.

Personally I wouldn't trust the "locally flat earth" model for distances much over the 10-20 km region, certainly not hundreds of km. But it does depend a lot on what you consider to be good enough accuracy. But certainly good enough for the distances in this question.

But... Are you really sure that Earth is not flat?

@Andrew: The library is intended for low-accuracy applications. For example, it uses the approximation cos(π/2 ⋅ x) ≈ 0.962(1 – x²), which has a maximum error of about 0.038. It this accuracy level the “locally flat Earth” approximation is valid for quite large distances at mid-latitudes.

@EdgarBonet I'm probably just too used to working in an environment where an error of 1 cm is unacceptable high ;-)

I have successfully used an Arduino + hobby GPS to get an accuracy within a few meters with an update every second using normal floating point on Arduino. This should be possible.
A 32-bit float has 24 bits of precision, and one 2^24th of half the Earth's circumference is about 1.2 meters, so the theoretical cap is roughly that.
If I recall correctly, you would get better accuracy for short distances on a 32-bit float using normal 2D trig than haversine, but both should work.
Check to make sure you are reading your GPS correctly and go over the equations again. Is everything converted to radians correctly for the trig? Make sure your version of PI has enough digits. Are you correctly parsing the GPS output value as degrees+decimal minutes? It is not a simple decimal degree number (like Google Maps coordinates would be) if it came from an NMEA message. Are there any configuration startup commands you need to send your GPS unit?
I think the fastest updates you can expect is a new coordinate every second, but I haven't used your specific GPS.

Uhm.. in fact you do not have to take into account the radius of Earth, but the emi-circumference. This means that the maximum resolution for a float is about 1.2 meters...

@frarugi87 wow, yeah, thats a dumb mistake. Thanks.

I have created Code to Calculate GPS Distances between Multiple Points on an Arduino Mega 2560 to 0.04 foot accuracy. I included in the Code "Functions" and Code to I used to keep track of Locations. They are not applicable to the Calculations but shows that you can bring in Points for both Distance from Rover To Base and Distance from Rover to next Point you are wanting to go to. It also calculates the Angles between the Base & Rover and Rover to Next Point. The angles are not Global but in reference to each of the points. I could not get Global Angles calculates to any precision that why I used Angles calculation between point. Serial.Print can substituted for lcd.print. From Zed-f9d UART1 Protocol Out ( 0+1 - UBX+NMEA)   Bob Brandt, Hartsburg MO.
Will Also Work with C94-M8P  UART1 Protocol Out
Calculates Feet to the nearest   0.04 Feet  Distance Between Points
Angles are Calculated with Reference to Base NOT Global
Degrees Whole Numbers NOT used for LongDiff but are here if Needed Example Below.
LongDiff = (( (88 * Secs2)- (88 * Secs1)) + ((5280 * Mins2)-(5280 * Mins1)));
Bob Brandt, Hartsburg MO.
    gpsData = "";
    while (Serial2.available()) {
    inChar = Serial2.read();
    gpsData += inChar;
    if (inChar == '$') {
    gpsData = Serial2.readStringUntil('\n');
    }  }
  String sGPRMC;
  sGPRMC = gpsData.substring(0, 5);
  if (sGPRMC == "GNRMC") {
    String  LattBase =    "3840.xxxx1";
    String  LongBase = "09214.8xxx4";
    float   Angles_and_TotalFeet;
    float   LattDiff;
    float   LongDiff;
    int       Mins1;
    int       Mins2;
    int        Deg;
    float    Secs1;
    float    Secs2;
    float    LatRovSecs;
    float    LonRovSecs;
    String  a1st;
    int     Ft_Per_Degree = 316800;
   LattRover = gpsData.substring(18, 28);
   LongRover = gpsData.substring(31, 42);
   int NS_POS = gpsData.substring(10, 35).indexOf('N');      // NS_POS  = North South Position Also Lattitude East West.
   lcd.setCursor(9, 2);
   lcd.print(LongRover);
  lcd.setCursor(10, 3);
  lcd.print(LattRover);
  if( Func == 0){
  if(Cutting_Phase == 2 &&  RunStart == false ){
     lcd.setCursor(5, 0);
  lcd.print("Next          "); }
  if( Cutting_Phase < 2 &&  RunStart  == false){
     lcd.setCursor(5, 0);
  lcd.print("Ready          "); }
  lcd.setCursor(12, 1);
  lcd.print("Location");  }
   if( Func == 1){
  lcd.setCursor(5, 0);
  lcd.print("Save Points");
  lcd.setCursor(12, 1);
  lcd.print("Location");  }
  lcd.setCursor(18, 0);
  lcd.print(Cutting_Phase);
  NS_POS = LongBase.indexOf('.');
  a1st   = String(LongBase.substring(0,NS_POS ).toInt());
  Deg = (a1st.substring(0, a1st.length()-2 )).toInt();
  Mins1 = (a1st.substring(a1st.length()-2 )).toInt();
  LastWord = a1st.substring(a1st.length(),2);
  Mins1 = LastWord.toInt();
  Secs1  = (LongBase.substring(NS_POS)).toFloat();
  Secs1 = Secs1 * 60;
  Ft_Per_Degree = 31680;
  NS_POS = LongRover.indexOf('.');
  a1st   = String(LongRover.substring(0,NS_POS).toInt());
  Deg = (a1st.substring(0, a1st.length()-2 )).toInt();
  LastWord = a1st.substring(a1st.length(),2);
  Mins2 = LastWord.toInt();
  Secs2  = (LongRover.substring(NS_POS)).toFloat();
  Secs2 = Secs2 * 60;
  LonRovSecs = Secs2;
  LongDiff = (( (88 * Secs2)- (88 * Secs1)) + ((5280 * Mins2)-(5280 * Mins1)));
  Ft_Per_Degree =  sin(Deg * (PI/180)) * 316800;
  NS_POS = LattBase.indexOf('.');
  a1st   = String(LattBase.substring(0,NS_POS ));
  Deg = (a1st.substring(0, a1st.length()-2)).toInt();
  LastWord = a1st.substring(a1st.length(),2);
  Mins1 = LastWord.toInt();
  Secs1  =(LattBase.substring(NS_POS)).toFloat();
  Secs1 = Secs1 * 60;
  NS_POS = LattRover.indexOf('.');
  a1st   = String(LattRover.substring(0,NS_POS ).toInt());
  Deg = (a1st.substring(0, a1st.length()-2)).toInt();
  LastWord = a1st.substring(a1st.length(),2);
  Mins2 = LastWord.toInt();
  Secs2  = (LattRover.substring(NS_POS)).toFloat();
  Secs2 = Secs2 * 60;
   LatRovSecs = Secs2;
  LattDiff  = (((88 * Secs2)- (88 * Secs1)) + ((5280 * Mins2)- (5280 * Mins1)));
  Angles_and_TotalFeet = sqrt(sq(LongDiff) + sq(LattDiff));
  lcd.setCursor(0, 2);
  lcd.print(Angles_and_TotalFeet  + String(" Ft  "));
  lcd.setCursor(19, 0);
  if (LattDiff > 0 &&  LongDiff > 0) {
   Intermead = 270 + atan((LongDiff) / (LattDiff)) * 57.29578;
   lcd.print("1");   }
  if ( LongDiff < 0 && LattDiff < 0) {
  Intermead =  90 + atan(( LongDiff ) / (LattDiff )) *  57.29578;
  lcd.print("2");  }
  if  (LongDiff  < 0 && LattDiff > 0) {
  Intermead  =  (atan((LongDiff) / (LattDiff)) * 57.29578) * -1;
   lcd.print("3");  }
  if  (LongDiff  > 0 && LattDiff < 0) {
  Intermead  = 270 + (atan((LongDiff) / (LattDiff)) * 57.29578);
   lcd.print("4");  }
  lcd.setCursor(0, 3);
  lcd.print("          ");
  lcd.setCursor(0, 3);
  lcd.print(Intermead + String(" Dg"));
 int value = (SavedLongitude[0]);    //Location to Go To.
 if ( value > 1   &&     RunStart) {       // RunStart tell program to Start Moving
  lcd.setCursor(0, 1);
  lcd.print("          ");
  lcd.setCursor(0, 1);
  lcd.print(YardLocation);                //Name of File to get Info
  LongBase = "";
  LattBase = "";
  LongBase  = SavedLongitude;
  NS_POS = LongBase.indexOf('.');
  a1st   = String(LongBase.substring(0,NS_POS ).toInt());
  Deg = (a1st.substring(0, a1st.length()-2 )).toInt();
  Mins1 = (a1st.substring(a1st.length()-2 )).toInt();
  Secs1  = (LongBase.substring(NS_POS)).toFloat();
  Secs1 = Secs1 * 60;
  LongDiff = (((88 * LonRovSecs)- (88 * Secs1)));
  LattBase  = SavedLatitude;
  NS_POS = LattBase.indexOf('.');
  a1st   = String(LattBase.substring(0,NS_POS ));
  Deg = (a1st.substring(0, a1st.length()-2)).toInt();
  Mins1 = (a1st.substring(a1st.length(),2 )).toInt();
  Secs1  =(LattBase.substring(NS_POS)).toFloat();
  Secs1 = Secs1 * 60;
  LattDiff = (((88 * LatRovSecs )- (88 * Secs1)));
  Angles_and_TotalFeet = sqrt(sq(LongDiff) + sq(LattDiff));
   lcd.setCursor(4, 0);
  lcd.print("        ");
  lcd.setCursor(5, 0);
  lcd.print(Angles_and_TotalFeet + String("'") ); // Rover and next point distance apart

   lcd.setCursor(19, 0);
 if (LattDiff > 0 &&  LongDiff > 0) {
   Intermead = 270 + atan((LongDiff) / (LattDiff)) * 57.29578;
   lcd.print("1");  }
if ( LongDiff < 0 && LattDiff < 0) {
  Intermead =  90 + atan(( LongDiff ) / (LattDiff )) *  57.29578;
  lcd.print("2");   }
if  (LongDiff  < 0 && LattDiff > 0) {
   Intermead  =  (atan((LongDiff) / (LattDiff)) * 57.29578) * -1;
   lcd.print("3");   }
if  (LongDiff  > 0 && LattDiff < 0) {
  Intermead  = 270 + (atan((LongDiff) / (LattDiff)) * 57.29578);
  lcd.print("4");  }
  Current_Heading = Intermead;
if ( Cutting_Phase == 1  && (Intermead > (headingDegrees - 1)) && (Intermead < (headingDegrees + 1))) {
 Cutting_Phase = 2;
 RunStart = false;
}

  lcd.setCursor(11, 0);
  lcd.print(Intermead + String("D"));
 delay(10);
  } else {
   lcd.setCursor(0, 1);
   lcd.print("            ");
  lcd.setCursor(0, 1);
  lcd.print(YardLocation);
  }

   }    }

headingDeg is from HMC-5983 Compass.   LongDiff = (( (88 * Secs2)- (88 * Secs1)) + ((5280 * Mins2)-(5280 * Mins1))); Add to it ((Deg* Ft_Per_Degree) - (Deg? * Ft_Per_Degree)) I noticed I left out (5280 * Mins2)-(5280 * Mins1) on last calculations.

There seems to be a lot of unnecessary capitalisation (which makes it rather difficult to read)

The position difference calculation part of the question has been handled by Edgar. Which leaves the heading to the child part.
To work out which direction the parent is walking in don't use change in position. Use the heading and velocity outputs from the GPS. These will be far more accurate than calculating the velocity based on the change in position.
As for rate of update it depends a lot on the GPS being used, the one you linked to indicates that it supports 10 Hz updates so you should be able to get a position and heading update 10 times per second. The default will be 1 Hz so you'll need to send the correct configuration command. This will however significantly increase battery usage.
Those low end GPS systems typically have a fair amount of latency but the values you get in the serial stream shouldn't be more than 100 ms old, easily good enough for something as slow as a person walking.

You may be interested in my NeoGPS library.  It is smaller, faster, more reliable and more accurate than all other libraries.  It preserves the full accuracy of the GPS locations (10 significant digits), even during distance and bearing calculations.  NeoGPS uses the equirectangular simplification suggested by Edgar at small distances, and switches to Haversine at large distances.  As you have discovered, naive floating-point calculations (like those in all other libraries) lose that accuracy at small distances.
If you want to try it, NeoGPS is available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.

It is smaller, faster, more reliable and more accurate than all other libraries Not true. I have a library where the position is always 0,0. It's not very accurate but it's a lot smaller and far faster.

The library I linked to in my answer sits somewhere between @Andrew's library and NeoGPS, both in terms of speed and accuracy.

@Andrew, like the watch that is exactly correct once per day, your library would be optimal at exactly one place on Earth.  ;)

@EdgarBonet, I enjoyed reading about that project.  The parser is basically a custom scanf... cute!  I was curious how NeoGPS version would compare.  It would still fit in an ATtiny85, using about half the RAM of TinyNav (67 bytes vs. 119) but almost twice the program space (7746 bytes vs. 4084).  The NeoGPS Distance & Bearing routines require the floating-point library.


text:
Sending information via USB/Serialport
Am I able to send instruction from my computer, from another compiler, via the Arduino USB port?
To put this in context, I'm doing some vision processing on my computer, with Visual Studio, and I want to send some motor output via USB for the Arduino to execute.

I imagine Code Gorilla's given you the proper, specific answer you needed. I simply wanted to address your first (more general) ask,

Am I able to send instruction from my computer, from another compiler, via the Arduino USB port?

... and mention some other ways I've done this before. As long the Arduino's listening to the serial port for some specific (or any) input coming in, you can use whatever you'd like to send a message to the COM port your Arduino's using.
You absolutely are not hemmed into using solely the Arduino IDE (or it's serial monitor) for serial communication.
For instance, I wrote a Python script that communicated with an Arduino R3 (Rx/Tx) via the COM port it was assigned via the PySerial library - before coming to Python, I'd been doing this through a MS Visual C# WPF that was connected to the COM port and communicating with the Arduino (Rx/Tx) (you might need to adjust baud rates here or there, if I recall). Just to give you some ideas.

You can do it in a number of ways, but essentially your PC is going to open a serial connection to the Arduino and send data to it which will be interpreted into state changes of the digital ports of the Arduino.  The content of the messages is up to you, as long as both ends know what it means.
Step 1 would be to learn how to drive the motors on the Arduino by writing a program that drives the correct ports.
Step 2 is to modify that program so that when you type 1180 in to the serial monitor the Arduino turns motor 1 180 degrees, etc.
Step 3 Start Visual Studio, press F1 and search MSDN for a Serial console program that you can 'borrow'.
Step 4 Check your new serial program can replace the serial monitor and you can still turn motor 1 to 180 degrees.
Step 5 Put a flowery GUI over you serial console and polish your turd. :)
It doesn't matter what the GUI does, its still just a serial client talking to the Arduino.  You could offer Bluetooth or Wi-Fi connections, but its essentially the same beast.

Assuming your project is along the lines of "finding something and pointing at it".
This youtube video shows an eye mounted on a stalk apparently controlled by servo motors (a type of positioning motor).  The title infers an Arduino controls the motors and is in turned controlled by desktop computer running a program making use of OpenCV libraries.  However no details are given.
An Arduino Uno is perfect for controlling servo motors as it contains a dedicated Atmel embedded processor. And there are Arduino servo libraries which make use of the Arduino processor's PWM hardware. This means controlling a servo can be as simple as several line of Arduino sketch code.
myservo.attach(2);  // attaches the servo on pin 2 to the servo object
myservo.write(0);   // sets the servo position to 0
delay(1000);        // waits for a second
myservo.write(90);  // sets the servo position to 90
delay(1000);        // waits for a second
myservo.write(180); // sets the servo position to 180

The USB port of an Arduino Uno normally implements serial port protocol layer inside the USB layer.  Many computers can deal with this easily.  So sending messages to an Arduino Uno is possible.  Here is a project (Arduino Playground - Simple Servo Control tutorial) where a (desktop) computer is controlling servo motors connected to an Arduino over the Arduino's USB port.

Could you provide the key points from the link you mention. Thanks.

Merely posting a link dose not constitute an answer under the rules of the stack exchange system.  If that's all you are going to do, you should post a comment.

I did not know that.  Thought direct was better.  Ok, changing.


text:
Why we can wake Arduino Uno from sleep using only pin 2?
Can we use other pin as an interrupt to wake Arduino Uno from sleep ?

It's not just Pin 2 that can wake from sleep. Depending on which sleep mode you are in different interrupts (both internal and external) can wake the chip up.
The datasheet contains this helpful table:

The external interrupts (pins 2 and 3 on the Uno, and only "Level" trigger mode), pin change interrupts, I2C address matching, and the watchdog are the only interrupts that can wake the chip from any sleep mode. Other interrupts only work in certain sleep modes since they require parts of the chip to still be running in order for the interrupt to fire.
So that means that yes you can use any pin you like (using the "Pin Change" Interrupts) to wake the chip.

Thank you Majenko for your answer. Actually, in my project, I'm using the EnableInterrupt library (https://github.com/GreyGnome/EnableInterrupt) which enable to extend the interrupt functionality to multiple pins in the Uno, do you think that this will help to use other pins in the Uno to wake up using interrupts ?

That is just a fancy wrapper for the Pin Change interrupts, so yes, it will wake the chip.

I think you also can use pin 3 (INT1), see link
There are two interrupts:

INT0, pin 2
INT1, pin 3

According to the link (among other techniques), an external interrupt can be used, so both INT0 and INT1 should be valid.


text:
Control a 5 volt water pump with an Arduino
I want to control (only on/off) a small water pump (5 V, 200 mA max.) with my Arduino.
I read something about NPN transistor, because the output pins of the Arduino can't supply enough current to the pump. However, I don't know how to choose the right transistor and how to connect it with my Arduino and my water pump.

i would use an n-channel logic-level mosfet; 1w is going to be pushing it for signal BJTs.

@dandavis: Note that 1 W is the power of the load. The switching transistor is not going to dissipate anywhere near that power.

@EdgarBonet: at least 0.6/5th of it will, and that can get little TO92s quite hot...

@dandavis: What does “0.6/5th” mean?

(0.6v / 5v) * 1w = 120mw to dissipate. that's actually probably fine now that i run the math. toasty, but not pushing it. cheers

To use an NPN, connect a power rail of 5V to the pump's positive terminal, and from its negative terminal wire it to the transistor's collector pin. Wire emitter to GND, and place a >=220 ohms resistor between your arduino control pin and the transistor base.
If instead using an N-channel MOSFET, wire load to drain, source to GND, and use a 4K7 pull-down on gate.
Also add a diode, with its anode at the pump's negative terminal, and cathode (white ring) at the positive terminal.

why do you need a resistor on the mosfet's gate? The MCU grounds the pin when deactivated, so is there an advantage to using an external resistor?

@dandavis yes, there is an advantage in that. The switching works best when the MOSFET is absolutely OFF when not absolutely ON. A transient could turn the MOSFET on, or the gate may not discharge quickly enough to allow for fast switching. I had problems with the latter, even on small MOSFETs, like 2N7000.

@dandavis No. The signal from the MCU would just go directly to ground, and the gate would never be charged.

Connect the output from the MCU directly to the gate. Connect the gate to a 4K7 resistor. Connect the other side of the resistor to ground. Optionally, if the gate has enough capacitance to surge the output, add a 220 ohms resistor in series from MCU output to gate.

@dandavis Why are your replies deleted?

i don't want to detract from the answer. was hoping you would edit... i thought you had meant to connect the gate via a resistor to the mcu...

I would only do this for large power MOSFETs to prevent surging. Regardless, it seems OP has flown away.

@dandavis: The pulldown on the MOSFET gate ensures it will be off even before your sketch starts, while the Arduino is running the bootloader. Otherwise it would float, as the Arduino pins are in the high-impedance state until you issue pinMode(pin, OUTPUT).