// Function declaration for dehex()
byte dehex(char c); // Get nibble value 0...15 from character c
void SendCTRL (String input) {
const char *hin = input.c_str(); // Get character array
int clen = input.length/2;
// Next line invalid in C++, ok in C99. Probably need to
// instead declare a fixed-length array, cmd[MAXCMDLEN], etc
char cmd[clen+1]; // Leave a byte for null terminator
for (int i=0; i < 2*clen; i+=2) {
cmd[i/2] = dehex(hin[i])<<4 +| dehex(hin[i+1]);
}
cmd[clen] = 0; // Null-byte terminator
digitalWrite(SSerialTxControl, RS485Transmit); // Enable RS485 Transmit
RS485Serial.write(cmd); // Send string someplace
delay(clen/4); // Wait for write to complete? What rate?
digitalWrite(SSerialTxControl, RS485Receive); // Disable RS485 Transmit
}
byte dehex(char c) { // Get nibble value 0...15 from character c
// Treat digit if c<'A', else letter
return c<'A'? c & 0xF : 9 + (c & 0xF);
// Above assumes that c is a 'hex digit' in 0...9, A or a ... F or f.
// It would make more sense to just use 16 consecutive characters,
// like eg 0123456789:;<=>? or @ABCDEFGHIJKLMNO so the above
// could just say `return c & 0xF;`
}
The first statement,
byte dehex(char c);is a function declaration for thedehex()function. It tells the C/C++ compiler the datatypes that the function accepts and returns. Note, instead of a function declaration at that point, one could instead put the function definition itself (which in the above followsSendCTRL(), adehex()caller that needs to knowdehex()'s datatypes). Some versions of the Arduino IDE appear to work ok without function declarations ahead of use, but almost all other C/C++ environments will not.In this edit I added
constbeforechar *hin = input.c_str();because ATE-ENGE reports “char *hin =input.c_str()is giving me an invalid conversion error from const char* to char*”. That error indicates the left-hand-side variable has a datatype different from that of the right-hand-side expression and an automatic conversion isn't available. Note, unfortunately the arduino.ccc_str()webpage doesn't specify the return type ofc_str().
Edit 3: Changed for (int i=0; i < clen; i+=2) to for (int i=0; i < 2*clen; i+=2) per notes in another question's answer.
Edit 4: Changed cmd[i/2] = dehex(hin[i])<<4 + dehex(hin[i+1]) to cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]) to avoid an operator precedence problem. The precedence of +, addition, is higher than that of <<, bitwise shift, which in turn is higher than that of |, bitwise OR. The unparenthesized expression with + adds 4 to dehex(hin[i+1]) and uses the total as a shift count; not at all as desired. Note, one can of course use parentheses to control the problem, as in the expression (dehex(hin[i])<<4) + dehex(hin[i+1])