Help!! Converting simple C++ program to Arduino LCD and keypad. Stuck

Hi, So I’m new to Arduino. Still learning. I want to convert a program that I made in C++ to LCD and keypad.

C++ version
#include
#include
#include <stdio.h>
using namespace std;

int main()
{
int n;
float sum = 0, i, value,sum2,tip;

/ask user for the number of items needed to calculate the total cost/
cout<<“Enter the number of items you want to add”<<endl;
cin>>n;

cout<<“Enter “<<n<<” cost for each item”<<endl;

//loop for input of each item cost then it is summed
for (i = 1; i <= n; i++)
{
cout<<"$";
//gets value of cost from user
cin>>value;
//sum of earch item
sum = sum + value;
}
sum2=((sum0.08)+sum);
cout<<"***********************************************"<<endl;
//total cost with tax included.
printf(“Total without tip is= %f\n”, (sum
0.08)+sum);
cout<<"***********************************************"<<endl;
char chose;
/ask the user if the tip in % or cash. only y for yes and n for no allowed./
do
{
cout<<“Is the tip in percent. Type y yes or n no?”<<endl;
cin>>chose;
}
while(chose != ‘y’&& chose != ‘n’);
if(chose==‘y’)
{
cout<<“what is the percent?”<<endl;
cin>>tip;
//takse %tip and divide it by 100
tip=(tip/100);

cout<<"***********************************************"<<endl;

cout<<“Total cost is :\n”<<(tip*sum2)+sum2<<endl;
cout<<"***********************************************"<<endl;
}

else if(chose==‘n’)
{
//if no %tip was givin but was given a float then this will be exucuted
cout<<“what is the tip amount?”<<endl;
cin>>tip;
cout<<“"<<endl;
//total cost whitch includes cost+tax and the tip
cout<<"Total cost is: "<<(sum*0.08)+sum+tip<<endl;
cout<<"
”<<endl;

}
return 0;
}

This is what I got so far. But I can’t get past clearing the screen after typing the number of items.

The most important part I really want to figure out for this loop is to find how many items you want to put in and add their total.

#include <LiquidCrystal.h> //import lcd library
#include <Keypad.h> //import keypad library

LiquidCrystal lcd(5, 4, 3, 2, 1, 0); //lcd pins
const byte ROWS = 4; // four rows
const byte COLS = 4; // four columns

boolean valOnePresent = false;
boolean final = false;
String n;
//char chose;

//value,sum2,tip;
//define the keymap
char keys [ROWS] [COLS] = {
// Y=yes, N=no, d=delete number, R=reset
{‘1’, ‘2’, ‘3’, ‘Y’},
{‘4’, ‘5’, ‘6’, ‘N’},
{‘7’, ‘8’, ‘9’, ‘.’},
{‘R’, ‘0’, ‘=’, ‘d’}
};
byte rowPins[ROWS] = {
6 , 7 , 8 , 9
}; //connect keypad ROW1, ROW2, ROW3, ROW4 to these arduino pins
byte colPins[COLS] = {
10, 12, 11, 13
}; //connect keypad COL1, COL2, COL3, COL4 to these arduino pins

//create the keypad
Keypad myKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup() {
lcd.begin(16, 2);
lcd.setCursor(3, 0);
lcd.print(“Welcome”);
delay(1000);
lcd.clear(); //clears the LCD screen and positions the cursor in the upper-left corner.
}

void loop()
{
lcd.setCursor(0, 0);
lcd.print(“Enter # of items”);

char key = myKeypad.getKey();

if (key != NO_KEY && (key == ‘1’ || key == ‘2’ || key == ‘3’ || key == ‘4’ || key == ‘5’ || key == ‘6’ || key == ‘7’ || key == ‘8’ || key == ‘9’ || key == ‘0’))
{
if (valOnePresent != true)
{
n = n + key;
int Length = n.length();
lcd.setCursor(0, 1); //to adjust one whitespace for operator
lcd.print(n);
}
else if (final == true && key != NO_KEY && key == ‘=’)
{
lcd.clear(); //wont clear "Enter # of items and “n”
int(n);i need to convrt string n to int n to use in the for loop
for (int i = 1; i <= n; i++)
{
//user inputs the cost of each n items
}
lcd.clear();
lcd.setCursor(15, 0);
lcd.autoscroll();
lcd.print(n);
}

}

}

I have been simulating the code at tinkercad. Which is a bit different from key layouts from my Arduino setup.

PLease use code tags

To translate your original code reasonably literally:

/*ask user for the number of items needed to calculate the total cost*/
   cout<<"Enter the number of items you want to add"<<endl;
   cin>>n;

you want to replicate the complete function of each line, a bit like:

  /*ask user for the number of items needed to calculate the total cost*/
   writeMessage("Enter the number of items you want to add");
   n= readNumber();

Then you need to figure out what, say, the readNumber() function has to do, e.g.

// read number from keypad until 'Y' pressed
// outputs digits to 2nd line of LCD
// returns: always returns a number
// 
int readNumber(){
  int n=0;
  char key;
  boolean done= false;

  while( ! done )
  {
    key = myKeypad.getKey();
    if( key == 'Y' )
      done= true;

    if( (key >= '0') && (key <= '9') )
      n= n*10 + key-'0';

    if( key == SOME_OTHER_KEY )
       do_other_key_function_here;

    // print number to LCD here
  };
  return n;
}

Yours,
TonyWilk

You might consider a short list at least to describe the program flow.

  1. Ask the number (N) of values from user
  2. Ask for N number of values from use summed into ‘sum’ variable
  3. Add 8% to sum into variable sum2
  4. Show total without Tip
  5. Ask if tip is in % , Y or N
  6. If answer is N, continue with step 10
  7. Ask for the percent number in %
  8. Show user what total will be with tip added
  9. Goto 1
  10. Ask for specific tip amount in tip
  11. Show user what total will be with tip added
  12. Goto 1

And I agree with TonyWilk that you need a routine to collect a floating point number and probably another to collect a Y or N answer. You could use the same number routine for integers and just use the integer component, or better yet modify it to be able to specify the number of valid decimals as an option.

So I’m unable to clear the screen when I get # of items N

 Enter # of Items
(number goes here)

I want the screen to clear once I get N when I click = (Enter) so I can then execute the for loop of the cost of each items N.

This is the code now

#include <LiquidCrystal.h> //import lcd library
#include <Keypad.h> //import keypad library
int readNumber();
int enter();


LiquidCrystal lcd(5, 4, 3, 2, 1, 0); //lcd pins
const byte ROWS = 4; // four rows
const byte COLS = 4; // four columns


//char chose;

//value(for loop),sum2 (sum of N items),tip; like to add............
//define the keymap
char keys [ROWS] [COLS] = {
  {'1', '2', '3', 'Y'},
  {'4', '5', '6', 'N'},
  {'7', '8', '9', '.'},
  {'C', '0', '=', 'd'}
};
byte rowPins[ROWS] = {
  6 , 7 , 8 , 9
}; //connect keypad ROW1, ROW2, ROW3, ROW4 to these arduino pins
byte colPins[COLS] = {
  10, 12, 11, 13
}; //connect keypad COL1, COL2, COL3, COL4 to these arduino pins

//create the keypad
Keypad myKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );


void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Welcome");
  delay(1000);
  lcd.clear(); //clears the LCD screen and positions the cursor in the upper-left corner.

}


void loop()
{
  lcd.setCursor(0, 0);
  lcd.print("Enter # of items");
  n= readNumber();
  if(enter()==true) // does nothing even a lcd.clear doesn't clear the screen????
  {
  lcd.clear();
  }
  /*for(int i=1;i<=n;i++)
  {
    
  }
  */
  
}

int readNumber(){
  int n=0;
  char key;
  boolean done= false;

  while( ! done )
  {
    key = myKeypad.getKey();
   // if( key == 'Y' )
     // done= true;
      //lcd.setCursor(0,1);
      //lcd.print(n);

    if( (key >= '0') && (key <= '9') )
      n= n*10 + key-'0';
      lcd.setCursor(0,1);
      lcd.print(n);

    //if( key == '=' )
      // lcd.setCursor(0,0);
       //lcd.clear();

    // print number to LCD here
  };
  return n;
}





int enter(){
  
  char key;
  boolean done= false;

  while( ! done )
  {
    key = myKeypad.getKey();
    if( key == '=' )
      lcd.setCursor(0,0);
      lcd.clear();

  }
  return enter;
}

I would choose different pins for your display. 0 and 1 are typically reserved for Serial out. And using Serial.print statements is the only way to really debug Arduino code.

But if you were printing something in your get number routine, I think you would find your software never leaves it. Only way out is for done to be true and you have the one line where that is possible commented out.

  while( ! done )
  {
    key = myKeypad.getKey();
   // if( key == 'Y' )
     // done= true;
      //lcd.setCursor(0,1);
      //lcd.print(n);

    if( (key >= '0') && (key <= '9') )
      n= n*10 + key-'0';
      lcd.setCursor(0,1);
      lcd.print(n);

    //if( key == '=' )
      // lcd.setCursor(0,0);
       //lcd.clear();

    // print number to LCD here
  };

WTF is this !!!

It looks like you are just thrashing about… add a line, comment a line out, compile it, run it, not working, comment a line out… and on and on

Just stop and think for a minute… what can this possibly be doing ?

Yours,
TonyWilk

I will agree that writing code this way is going to take you years to finish just this project. Mentally walk though what the code is doing as if you were the processor interpreting the lines of code vs just compile and pray. Start with something easier! If it is a library call then you need to understand how to use it, even if you don’t know how the library actually works. But when it is YOUR code, you MUST understand it completely. (or just get lucky which never happens). And change LCD pins off 0 and 1 so you can start using print statements to debug what is happening. I have been programming for over 45 years and I still use print statements to debug and find why code does not work the way I think it will.

Entering floating numbers from a keypad is not difficult, but it is not exactly a beginner project.

Here is a small example to help you get started. (Mostly debugged but I don’t own a 4x4 keypad).

You should think through each step of “your” main loop from here and get it working one small step at a time.

#include <LiquidCrystal.h> //import lcd library
#include <Keypad.h> //import keypad library

LiquidCrystal lcd(5, 4, 3, 2, 1, 0); //lcd pins  <---CHANGE THIS
const byte ROWS = 4; // four rows
const byte COLS = 4; // four columns


//define the keymap
char keys [ROWS] [COLS] = {
  {'1', '2', '3', 'Y'},
  {'4', '5', '6', 'N'},
  {'7', '8', '9', '.'},
  {'C', '0', '=', 'd'}
};
byte rowPins[ROWS] = {
     6 , 7 , 8 , 9
}; //connect keypad ROW1, ROW2, ROW3, ROW4 to these arduino pins
byte colPins[COLS] = {
     10, 12, 11, 13
}; //connect keypad COL1, COL2, COL3, COL4 to these arduino pins

//create the keypad
Keypad myKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Welcome");
  delay(1000);
  lcd.clear(); //clears the LCD screen and positions the cursor in the upper-left corner.
}


void loop() {
  lcd.setCursor(0, 0);
  lcd.print("No of items: ");
  int n = getNumber(0);
  lcd.clear();
  lcd.setCursor(0, 1);
  lcd.print(n);
  lcd.print("? (Y or N)");
  if (getYesNo()) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("First Number: ");
    float n1 = getNumber(2);
    lcd.setCursor(0, 1);
    lcd.print("1st number = ");
    lcd.print(n1);
    while (1);
  }
}


bool getYesNo() {
  char Key = 0;
  while (1) {
    while (!(Key = myKeypad.getKey()));
    if (Key == 'Y' or Key == 'N') {
      lcd.setCursor(0, 1);
      lcd.print(Key);
      return (Key == 'Y');
    }
  }
}


float getNumber(byte decimalLimit) {
  while (1) {
    char Key;
    char value[11] = "          ";
    byte keyCount = 0;
    byte decimalCount = 0;
    bool decimalMode = false;
    lcd.setCursor(0, 1);
    lcd.print(value);            //Clear the entry line
    while ( 1 ) {
      while (!(Key = myKeypad.getKey()));
      if (keyCount < 10 and (((Key >= '0' && Key <= '9') || (Key == '.' && !decimalMode && decimalLimit > 0)) && decimalCount < decimalLimit + 1)) {
        value[keyCount++] = Key; //save next number or decimal place
        value[keyCount] = 0;
        if (decimalMode) ++decimalCount;
        if (Key == '.') decimalMode = true;
      }
      if (Key == '=' or Key == 'Y' or Key == 'R') break;  //Stop or Reset
      lcd.setCursor(0, 1);
      lcd.print(value);
    }
    if (Key != 'R') return (float) atof(value);
  }
}

.

Thanks for everything! I am new to coding. Sorry if it's not good yet. I have been teaching myself basic C++ for the past 6 months. A skill that is worth having even at a basic level. Wanted to get into some Arduino kits to make small things as well as increase my knowledge of programming. I like the tips and the help from both of you wzaggle and TonyWilk! Thanks!