0

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?

user28282
  • 55
  • 1
  • 5

1 Answers1

1

You have the number. It's made up of two nibbles, each representing 4 bits (1 hex character).

If you want to do a manual conversion take the first nibble (AND with 240) add it's value to "0" then do the same for the lower nibble (AND with 15).

OR

What I would do is use:

char HexString[3]; 
sprintf(HexString,"%02X",HexInt);

since you're not dealing with floats, you're good to go.

OR

edit: I recalled a printf function that we put together once before, I don't know if it would work with SoftwareSerial, so you might have to play around with it a bit, but as a 3rd option, you could try the following. I don't have access to an Arduino or compiler at the moment, otherwise I'd have a play with this right now.

Before your setup:

// Function that printf and related will use to print
int serial_putchar(char c, FILE* f) {
    if (c == '\n') serial_putchar('\r', f);
    return Serial.write(c) == 1? 0 : 1;
}

FILE serial_stdout;

In your setup, add:

// Set up stdout
fdev_setup_stream(&serial_stdout, serial_putchar, NULL, _FDEV_SETUP_WRITE);
stdout = &serial_stdout;

in your loop, change your assignment to:

HexString = printf("%02X",HexInt);

from: https://arduino.stackexchange.com/a/480/304

Madivad
  • 1,372
  • 8
  • 26