uint8_t command_line[100];
uint8_t command_line_len = 0;
void setup() {
// put your setup code here, to run once:
uint32_t start_time = millis();
// Wait up to 2 seconds for Serial port...
while (!Serial && ((millis() - start_time) < 2000))
;
Serial.begin(115200);
SetupSerialPort(1, 1, 0);
pinMode(13, OUTPUT);
delay(1000);
}
HardwareSerial *pserial = 0;
void SetupSerialPort(uint8_t ser, uint8_t tx, uint8_t rx)
{
// Close previous
if (pserial)
pserial->end();
pserial = 0;
switch (ser)
{
case 1:
pserial = &Serial1;
break;
case 2:
pserial = &Serial2;
break;
case 3:
pserial = &Serial3;
break;
#ifdef HAS_KINETISK_UART3
case 4:
pserial = &Serial4;
break;
#endif
#ifdef HAS_KINETISK_UART4
case 5:
pserial = &Serial5;
break;
#endif
}
if (pserial)
{
if (tx != 0xff)
pserial->setTX(tx);
if (rx != 0xff)
pserial->setRX(rx);
pserial->begin(115200);
Serial.printf("Starting Serial test on Serial%d using TX:%d RX:%d\n\r", ser, tx, rx);
Serial.println("Text entered on Serial will echo to selected Serial port");
Serial.println("lines start with # will choose new Serial port TX RX");
pserial->println("Text entered here echos on debug terminal");
}
}
uint8_t* GetNextCmdNum(uint8_t *psz, uint8_t *pnum)
{
*pnum = 0; // clear it out just in case.
if ((psz == 0) || (*psz == 0)) {
*pnum = 0xff; //return error
return 0; // bail if at end
}
// Skip all leading num number characters...
while ((*psz < '0') || (*psz > '9'))
{
if (*psz == 0)
return 0; // end of the line...
psz++;
}
while ((*psz >= '0') && (*psz <= '9'))
{
*pnum = *pnum * 10 + (*psz++ - '0');
}
return psz;
}
void loop() {
// Look for input from Selected Serial port
int ch;
if (pserial)
{
while ((ch = pserial->read()) != -1)
Serial.write((uint8_t)ch);
}
// Now See if anything came in on Serail
while ((ch = Serial.read()) != -1)
{
if (pserial)
pserial->write((uint8_t)ch);
if ((ch >= 10) && (ch <= 15))
{
// Assume we have a command line
command_line[command_line_len] = 0; // make sure null terminated
if ((command_line_len > 1) && (command_line[0] == '#'))
{
uint8_t ser, tx, rx;
uint8_t *psz = GetNextCmdNum(&command_line[1], &ser);
psz = GetNextCmdNum(psz, &tx);
psz = GetNextCmdNum(psz, &rx);
SetupSerialPort(ser, tx, rx);
}
command_line_len = 0; // clear out line
}
else
command_line[command_line_len++] = (uint8_t)ch;
}
}