Strings in Zahlen umwandeln

Hi Leute

Ich habe folgendes Problem:

Ich wollte eine "Digitline" erstellen bei welcher eine Zufallszahl generiert wird und man diese Zahl dann mit einem Keypad eingeben muss. Das ganze wird auf einem LCD-Display(16x2) dargestellt.

Hier der Code:

#include <Keypad.h>
#include <LiquidCrystal.h>

const byte ROWS = 4;
const byte COLS = 3;
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {22,23,24,25};
byte colPins[COLS] = {26,27,28};
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS);
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

int tonePin = 29;
long randNumber = random(0, 1000000);
String input = ("");

void setup() {
Serial.begin(9600);
lcd.begin(16,2);
lcd.clear();
lcd.print("Zufalszahlen");
lcd.setCursor(0,1);
lcd.print("mit Keypad");
tone(tonePin, 2500, 500);
delay(2000);
lcd.clear();
lcd.print("Zufallszahl");
lcd.setCursor(0,1);
lcd.print(randNumber);
}

void loop() {
char keys = keypad.getKey();

if (keys) {
event();
input = (input + keys);
lcd.clear();
lcd.print(randNumber);
lcd.setCursor(0,1);
lcd.print(input);
}

if (keys == '#') {
randNumber = random(0, 1000000);
}

if (keys == '*') {
int inputInteger = atoi(input);
if (inputInteger == randNumber) {
lcd.clear();
lcd.print("O.K");
tone(tonePin, 1000, 250);
delay(100);
tone(tonePin, 500, 250);
delay(2000);
lcd.clear();
} else {
lcd.clear();
lcd.print("HAHAHAHAH");
delay(1250);
tone(tonePin, 500, 500);
lcd.clear();
}
}
}

void event() {
tone(tonePin, 1500, 50);
delay(10);
}

Nun muss ich den String "input" in eine Zahl umwandeln um das dann mit der "randNumber" zu vergleichen.

Ich hoffe ihr könnt mir helfen.

Gruss Kevin

Random_Numbers.ino (1.42 KB)

  char keys = keypad.getKey();

The getKey() function returns ONE key. Not multiple keys. Using a plural variable name is not a good idea.

String input = ("");

Nor are using unnecessary parentheses or the String class.

    event();

Function names should reflect what the function does. event() does not give a clue what the function does.

    int inputInteger = atoi(input);

The atoi() function does not take a String. It takes a string. You have three choices. Use the String::toCharArray() method to get the string from the String. Use the String::toInt() method, instead of atoi(). Or, best, ditch the String class altogether.