String comdata1 = ""; String voltage=""; void setup() { Serial.begin(9600);//串口和Arduino之间的通信 } void loop() { while (Serial.available() > 0) { comdata1 += char(Serial.read()); //每次读一个char字符,并相加 delay(2); voltage=comdata1.substring(4,7);//截取需要的字符串 } if(comdata1.length()> 0) { unsigned long ret; for(char i=0, n=voltage.length(); i!=n; ++i) { char ch=voltage; int val = 0; if('0'<=ch && ch<='9') val = ch - '0'; else if('a'<=ch && ch<='f') val = ch - 'a' + 10; else if('A'<=ch && ch<='F') val = ch - 'A' + 10; else continue; // skip non-hex characters ret=ret*16+val; } Serial.println(voltage); Serial.println(ret); comdata1 = ""; voltage= ""; } delay(2000); }
比如comdata1显示01 03 20 00 21 8D D8 00 01 38 75 0D 0A voltage显示21 8D D8 0D 0A, 但是ret始终是0, 不知道哪里有问题。
如果程序是这样输出正常 String voltage="00 21 8D D8"; char ch; void setup() { Serial.begin(9600); }
void loop() { unsigned long ret; for(int i=0, n=voltage.length(); i!=n; ++i) { ch = voltage; int val = 0; if('0'<=ch && ch<='9') val = ch - '0'; else if('a'<=ch && ch<='f') val = ch - 'a' + 10; else if('A'<=ch && ch<='F') val = ch - 'A' + 10; else continue; // skip non-hex characters ret = ret*16 + val; } Serial.println(ret); delay(1000); } ret=2199000
|