Arduino十六进制到字符串解码器不起作用



我正在使用LCD屏幕(显示十六进制以及解码值),键盘(输入十六进制代码)和按钮(按下它来解码十六进制值)创建一个十六进制-> STR解码器。解码器有时工作,但有时它会出现故障并显示意外值。

#include <Keypad.h>
#include<LiquidCrystal.h>
String hex; // store the hex values
String text; // store the decoded text
int calcButton = 0;
const byte ROWS = 4; 
const byte COLS = 4; 
char hexaKeys[ROWS][COLS] = {
{'1', '2', '3', 'F'},
{'4', '5', '6', 'E'},
{'7', '8', '9', 'D'},
{'A', '0', 'B', 'C'}
};
byte rowPins[ROWS] = {9, 8, 7, 6}; 
byte colPins[COLS] = {13, 12, 11, 10}; 
Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS); 
LiquidCrystal lcd(5, 4, 3, 2, A0, A1);
char nibble2c(char c) {
if ((c>='0') && (c<='9'))
return c-'0' ;
if ((c>='A') && (c<='F'))
return c+10-'A' ;
if ((c>='a') && (c<='a'))
return c+10-'a' ;
return -1 ;
}
char hex2c(char c1, char c2) {
if(nibble2c(c2) >= 0)
return nibble2c(c1)*16+nibble2c(c2) ;
return nibble2c(c1) ;
}
// resets string values and clears screen
void erase() {
hex = "";
Serial.println(hex);
text = "";
lcd.clear();
lcd.setCursor(0,0);
}
// decode the hex values
String calculate(String hex) {
if (hex.length()%2 != 0) {
lcd.setCursor(0,0);
lcd.print("No of characters");
lcd.setCursor(0,1);
lcd.print("needs to be even");
delay(2000);
erase();
}
else {
for (int i = 0; i < hex.length() - 1; i+=2){
for (int j = 1; j < hex.length(); j+=2){
text += hex2c(hex[i], hex[j]);
}
}
}
}

void setup() {
pinMode(A2, INPUT);
lcd.begin(16, 2);
lcd.setCursor(0,0);
Serial.begin(9600);
}
void loop() {
calcButton = digitalRead(A2); // decode button
char customKey = customKeypad.getKey();
// if keypad is pressed, add hex values to str
if (customKey){
lcd.print(customKey);
hex += customKey;
Serial.println(hex);
}
// if button is pressed, decode
if (calcButton == 1) {
lcd.clear();
calculate(hex);
hex = "";
lcd.print(text);
text = "";
delay(1500);
lcd.clear();
}
}

我输入49并得到I(这是正确的),但是当我输入4949时,我希望输出是II但它输出IIII,当我输入时6F期望o整个屏幕模糊和故障。

问题就在这里:

for (int i = 0; i < hex.length() - 1; i+=2){
for (int j = 1; j < hex.length(); j+=2){
text += hex2c(hex[i], hex[j]);
}
}

请注意,您length()*length()/4遍历十六进制字符串,将字符串中的每个偶数十六进制字符与字符串中的每个奇数字符(而不仅仅是紧随其后的字符)组合在一起。对于两位十六进制字符串,这有效,因为只有一个奇数和一个偶数索引字符;对于较长的字符串,您会得到错误的结果。

494949组合在一起,然后49(错误!),然后49(错误!),然后49,这给了你49494949应该给出

的结果,而不是4949

。你想要的只是:

for (int i = 0; i < hex.length() - 1; i+=2){
text += hex2c(hex[i], hex[i+1]);
}

最新更新