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

时间:2019-05-03 14:14:03

标签: arduino arduino-uno arduino-c++

我正在使用LCD屏幕(显示HEX和解码值),小键盘(输入HEX代码)和按钮(按下以对其进行解码)创建HEX-> 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时,整个屏幕就会模糊和出现毛刺。

1 个答案:

答案 0 :(得分:0)

问题在这里:

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次,将字符串中的每个偶数十六进制字符与字符串中的每个奇数字符组合在一起,而不仅仅是紧随其后的那个。对于两位数的十六进制字符串,这是可行的,因为只有一个奇数索引和一个偶数索引字符;对于更长的字符串,您会得到错误的结果。

4949将合并4(#0)和9(#1),然后合并4(#0)和9(#3) (错误!),然后是4(#2)和9(#1)(错误!),然后是4(#2)和9(#3) ,这将为您提供49494949而不是4949给出的结果。

您想要的只是:

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