This example allows you to connect your debug terminal to some other serial-connected device on the system. You can then type AT commands at the terminal and get responses back for the serially connected device. Should work with something like an ESP8266 or similar connected in to the Arduino header.

main.cpp

Committer:
AnnaBridge
Date:
2017-11-10
Revision:
0:0f1c0f6579ab

File content as of revision 0:0f1c0f6579ab:

#include "mbed.h"

UARTSerial pc(USBTX, USBRX);
UARTSerial device(MBED_CONF_APP_UART1_TX, MBED_CONF_APP_UART1_RX);

static void copy_some(FileHandle *out, FileHandle *in) {
    // To ensure performance, allow to read multiple bytes at once, although
    // we don't expect to read many in practice.

    // read() will return immediately, as we've already
    // checked that `in` is ready with poll()
    char buffer[32];
    ssize_t read = in->read(buffer, sizeof buffer);
    if (read <= 0) {
        error("Input error");
    }

    // Then write them all out. Assuming output port is similar speed to input,
    // this may block briefly, but not significantly.
    ssize_t written = 0;
    while (written < read) {
        ssize_t w = out->write(buffer + written, read - written);
        if (w <= 0) {
            error("Output error");
        }
        written += w;
    }
}

int main() {
    char buffer[32];
    pollfh fds[2];

    fds[0].fh = &pc;
    fds[0].events = POLLIN;
    fds[1].fh = &device;
    fds[1].events = POLLIN;

    while (1) {
        // Block until either of the 2 ports is readable (or has an error)
        poll(fds, 2, -1);

        if (fds[0].revents) {
            copy_some(fds[1].fh, fds[0].fh);
        }
        if (fds[1].revents) {
            copy_some(fds[0].fh, fds[1].fh);
        }
    }
}