Calculate checksum(hex) of string with ASCII(unsigned int). Use to detected communication error.
Diff: CheckSum.h
- Revision:
- 0:b3a521e42246
diff -r 000000000000 -r b3a521e42246 CheckSum.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/CheckSum.h Wed Oct 21 02:10:40 2015 +0000 @@ -0,0 +1,70 @@ +/** Calculate checksum(hex) of string with ASCII(unsigned int). + * Use to detected communication error. + */ + +/** @code + #include "mbed.h" +#include "CheckSum.h" + +DigitalOut led[]= {LED1, LED2, LED3, LED4}; +Serial pc(USBTX, USBRX); +int main() +{ + string str, tmp, checksum; + str= ""; + int idx; + bool ans; + while(true) { + led[0]= !led[0]; + if(pc.readable()) + str += pc.getLine(); + idx= str.find("\r\n"); + if(idx != string::npos) { + led[1]= !led[1]; + tmp= str.substr(0, idx); + str= str.substr(idx+ 2); + + checksum= CheckSum::calc(tmp); + ans= CheckSum::compare(tmp, checksum); + pc.printf("%s\t%s.\r\n", tmp.c_str(), checksum.c_str()); + if(ans) + pc.printf("TRUE"); + for(int i= 1; i < 5; i++) { + checksum= CheckSum::calc(tmp, i); + ans= CheckSum::compare(tmp, checksum); + pc.printf("%s\t%s.\r\n", tmp.c_str(), checksum.c_str()); + if(ans) + pc.printf("TRUE"); + } + } + } +} + @endcode + */ + +#pragma once +#include "mbed.h" + +#include "StrLib.h" + +class CheckSum +{ +public: + /** Create checksum (hex). + * @param; str: target + * Byte: returnend string size[B]. + * @return; The end of hex checksum. + */ + static string calc(string str, int Byte= 1); + + /** Compare Check. + * @param; str: target. + * sum: checksum of target. + * @return; true or false. + * if target equals to sum, returned true. + * else, returned false. + */ + static bool compare(string str, string sum); +}; + +// EOF \ No newline at end of file