diff --git a/libs/core/enums.d.ts b/libs/core/enums.d.ts index 4c9197d3..080eeb67 100644 --- a/libs/core/enums.d.ts +++ b/libs/core/enums.d.ts @@ -519,6 +519,8 @@ declare namespace led { P14 = 21, // MICROBIT_ID_IO_P14 P15 = 22, // MICROBIT_ID_IO_P15 P16 = 23, // MICROBIT_ID_IO_P16 + USB_TX = 1001, + USB_RX = 1002, } diff --git a/libs/core/serial.cpp b/libs/core/serial.cpp index 82a5a979..251c6cc4 100644 --- a/libs/core/serial.cpp +++ b/libs/core/serial.cpp @@ -2,6 +2,7 @@ #define MICROBIT_SERIAL_READ_BUFFER_LENGTH 64 +// make sure USB_TX and USB_RX don't overlap with other pin ids enum SerialPin { P0 = MICROBIT_ID_IO_P0, P1 = MICROBIT_ID_IO_P1, @@ -11,7 +12,9 @@ enum SerialPin { P13 = MICROBIT_ID_IO_P13, P14 = MICROBIT_ID_IO_P14, P15 = MICROBIT_ID_IO_P15, - P16 = MICROBIT_ID_IO_P16 + P16 = MICROBIT_ID_IO_P16, + USB_TX = 1001, + USB_RX = 1002 }; enum BaudRate { @@ -142,6 +145,20 @@ namespace serial { return buf; } + bool tryResolvePin(SerialPin p, PinName& name) { + switch(p) { + case SerialPin::USB_TX: name = USBTX; return true; + case SerialPin::USB_RX: name = USBRX; return true; + default: + auto pin = getPin(p); + if (NULL != pin) { + name = pin->name; + return true; + } + } + return false; + } + /** * Set the serial input and output to use pins instead of the USB connection. * @param tx the new transmission pin, eg: SerialPin.P0 @@ -158,10 +175,10 @@ namespace serial { //% rx.fieldOptions.tooltips="false" //% blockGap=8 void redirect(SerialPin tx, SerialPin rx, BaudRate rate) { - MicroBitPin* txp = getPin(tx); if (!txp) return; - MicroBitPin* rxp = getPin(rx); if (!rxp) return; - - uBit.serial.redirect(txp->name, rxp->name); + PinName txn; + PinName rxn; + if (tryResolvePin(tx, txn) && tryResolvePin(rx, rxn)) + uBit.serial.redirect(txn, rxn); uBit.serial.baud((int)rate); }