我一直试图从arduino键盘读取多个字符串,但似乎第一个字符串总是附加到第二个字符串,我不知道为什么?当我打印studentNumber时,访问代码加上星号会附加到studentNumber,这可能是什么原因造成的?请帮助,非常感谢。
#include <Keypad.h>
#include <LiquidCrystal.h>
#include <Servo.h>
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {10, 9, 8, 7}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {13, 12, 11}; //connect to the column pinouts of the keypad
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(A0, A1, A2, A3, A4, A5);
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
char holdKeys[] = {};
int i = 0;
int j = 0;
char accessCode[5];
char holdMaskedCode[5];
char holdMaskedNumber[8];
char studentNumber[9];
String accessCodeString;
Servo servo;
void setup() {
// put your setup code here, to run once:
servo.attach(5);
lcd.begin(16, 4);
lcd.setCursor(0,0);
lcd.print("Welcome");
lcd.setCursor(0,0);
pinMode(4, OUTPUT);
delay(2000);
lcd.clear();
lcd.print("Access Code");
//keypad.addEventListener(getAccessCode);
}
void loop()
{
char key = keypad.getKey();
if(key)
{
if(i < 5)
{
accessCode[i] = key;
holdMaskedCode[i] = '*';
lcd.setCursor(1,2);
lcd.print(String(holdMaskedCode));
if(i == 4)
{
lcd.clear();
lcd.setCursor(1,2);
accessCodeString = String(accessCode);
lcd.clear();
lcd.print("Student Number");
}
i++;
}
else
{
if(j < 9)
{
studentNumber[j] = key;
holdMaskedNumber[j] = '*';
lcd.setCursor(0,2);
lcd.print(holdMaskedNumber);
if(j == 8)
{
lcd.clear();
String number = String(studentNumber);
lcd.print(number);
delay(1000);
lcd.clear();
for(int i =0; i<10; i++)
{
lcd.print("Please wait.");
delay(500);
lcd.clear();
lcd.print("Please wait..");
delay(500);
lcd.clear();
lcd.print("Please wait...");
delay(500);
lcd.clear();
}
digitalWrite(4, HIGH);
for(int k =0; k<=180; k+=2)
{
servo.write(k);
delay(15);
}
setup();
}
j++;
}
}
}
}
答案 0 :(得分:0)
char accessCode[5];
...
accessCode[i] = key;
....
if(i == 4)
{
lcd.clear();
lcd.setCursor(1,2);
accessCodeString = String(accessCode);
这里不是空终止accessCode
所以当你将它转换为字符串时,转换会运行到内存中,从而获取其他随机垃圾。
accessCode
应该 6 字节长,在进行转换之前,请终止它,即
accessCode[5] = 0; // terminate string
accessCodeString = String(accessCode);