I am trying to read digits (number from 0 to 255) from Serial port, convert them to HEX String and send them using SoftwareSerial as HEX.
For example: when I send '60' trough the serial port, the SoftwareSerial will send '3C'
currently I am using the following code:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 4); // RX, TX
String inputString = "";
boolean stringComplete = false;
int HexInt = 0;
String HexString = "00";
void setup() {
Serial.begin(115200);
mySerial.begin(38400);
inputString.reserve(200);
delay(500);
Serial.println("");
mySerial.println("");
}
void loop() {
serialEvent();
if(stringComplete) {
HexInt = inputString.toInt();
HexString = String(HexInt,HEX);
if (HexInt<16) HexString = "0" + HexString ;
HexString.toUpperCase();
mySerial.println(HexString);
Serial.println(inputString); //debug
stringComplete = false;
inputString = "";
}
}
void serialEvent() {
while (Serial.available()) {
char inChar = (char)Serial.read();
if (inChar == '\n') continue;
if (inChar == '\r') {
stringComplete = true;
if (inputString == "") inputString = "NULL";
inputString.toUpperCase();
continue;
}
inputString += inChar;
}
}
My question is: Is there a more elegant / effective way to perform the same outcome?
char HexString[3];, you need space for the null terminator at the end of the string. And depending on the source of the data input it may make sense to either use snprintf or verify that the value is never outside the expected range. It pays to always be paranoid about buffer overflows. – Andrew Aug 01 '17 at 16:340x05,HexString[0]='0',HexString[1]='5',HexString[2]=0. – Madivad Aug 02 '17 at 00:41mySerial.println("GR+" + HexString);and I get an error regarding char and string cannot be added together. – user28282 Aug 03 '17 at 06:18HexStringnow contain? guessing by the error it's a char since "GR+" is a string. In the mean time and since it's just the.println()you're having a problem with here, just use multiple.print()and a.println()to achieve the same thing – Madivad Aug 03 '17 at 14:49print("GR+")followed by aprintln(HexString). thank you! – user28282 Aug 08 '17 at 11:35