unsigned long baud = 115200;
const int dtr_pin = A0;
const int rts_pin = A1;
const int led_pin = 13;
void setup()
{
pinMode(led_pin, OUTPUT);
digitalWrite(led_pin, LOW);
digitalWrite(dtr_pin, HIGH);
pinMode(dtr_pin, OUTPUT);
Serial.begin(baud); // USB, communication to PC or Mac
Serial1.begin(baud); // communication to hardware serial
}
long led_on_time=0;
byte buffer[80];
unsigned char prev_dtr = 0;
unsigned char prev_rts = 0;
void loop()
{
unsigned char dtr, rts;
int rd, wr, n;
// check if any data has arrived on the USB virtual serial port
rd = Serial.available();
if (rd > 0) {
// check if the hardware serial port is ready to transmit
wr = Serial1.availableForWrite();
if (wr > 0) {
// compute how much data to move, the smallest
// of rd, wr and the buffer size
if (rd > wr) rd = wr;
if (rd > 80) rd = 80;
// read data from the USB port
n = Serial.readBytes((char *)buffer, rd);
// write it to the hardware serial port
Serial1.write(buffer, n);
// turn on the LED to indicate activity
digitalWrite(led_pin, HIGH);
led_on_time = millis();
}
}
// check if any data has arrived on the hardware serial port
rd = Serial1.available();
if (rd > 0) {
// check if the USB virtual serial port is ready to transmit
wr = Serial.availableForWrite();
if (wr > 0) {
// compute how much data to move, the smallest
// of rd, wr and the buffer size
if (rd > wr) rd = wr;
if (rd > 80) rd = 80;
// read data from the hardware serial port
n = Serial1.readBytes((char *)buffer, rd);
// write it to the USB port
Serial.write(buffer, n);
// turn on the LED to indicate activity
digitalWrite(led_pin, HIGH);
led_on_time = millis();
}
}
// check if the USB virtual serial port has raised DTR
dtr = Serial.dtr();
if (dtr && !prev_dtr) {
digitalWrite(dtr_pin, dtr);
}
prev_dtr = dtr;
// check if the USB virtual serial port has raised RTS
rts = Serial.rts();
if (rts && !prev_rts) {
digitalWrite(rts_pin, rts);
}
prev_rts = rts;
// if the LED has been left on without more activity, turn it off
if (millis() - led_on_time > 3) {
digitalWrite(led_pin, LOW);
}
// check if the USB virtual serial wants a new baud rate
if (Serial.baud() != baud) {
baud = Serial.baud();
Serial1.begin(baud);
}
}