Created
October 13, 2022 09:43
-
-
Save tobymarsden/190d08b78014eb7ac877e7398d52703b to your computer and use it in GitHub Desktop.
HexPrint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
A tiny little hacked-together class to overload Serial.write to output hex to serial monitor, useful for debugging binary data e.g. protobufs | |
Usage, e.g. for debugging a nanopb stream wrapped by PacketIO: | |
packetio::COBSPrint cobs_out(hex_print); | |
pb_ostream_s pb_out = as_pb_ostream(cobs_out); | |
or for raw nanopb: | |
pb_ostream_s pb_out = as_pb_ostream(hex_print); | |
*/ | |
class HexPrint : public Print | |
{ | |
public: | |
void printHex(int num, int precision) | |
{ | |
char tmp[16]; | |
char format[128]; | |
sprintf(format, "%%.%dX", precision); | |
sprintf(tmp, format, num); | |
Serial.print(tmp); | |
} | |
virtual size_t write(const uint8_t *buffer, size_t size) { | |
size_t n = 0; | |
while (size--) { | |
printHex(*buffer++, 2); | |
n++; | |
} | |
return n; | |
} | |
virtual size_t write(const uint8_t val) { | |
printHex(val, 2); | |
return 1; | |
}; | |
} hex_print; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment