Anna Bridge / Mbed OS UARTSerial_Example2
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 
00003 UARTSerial pc(USBTX, USBRX);
00004 UARTSerial device(MBED_CONF_APP_UART1_TX, MBED_CONF_APP_UART1_RX);
00005 
00006 static void copy_some(FileHandle *out, FileHandle *in) {
00007     // To ensure performance, allow to read multiple bytes at once, although
00008     // we don't expect to read many in practice.
00009 
00010     // read() will return immediately, as we've already
00011     // checked that `in` is ready with poll()
00012     char buffer[32];
00013     ssize_t read = in->read(buffer, sizeof buffer);
00014     if (read <= 0) {
00015         error("Input error");
00016     }
00017 
00018     // Then write them all out. Assuming output port is similar speed to input,
00019     // this may block briefly, but not significantly.
00020     ssize_t written = 0;
00021     while (written < read) {
00022         ssize_t w = out->write(buffer + written, read - written);
00023         if (w <= 0) {
00024             error("Output error");
00025         }
00026         written += w;
00027     }
00028 }
00029 
00030 int main() {
00031     char buffer[32];
00032     pollfh fds[2];
00033 
00034     fds[0].fh = &pc;
00035     fds[0].events = POLLIN;
00036     fds[1].fh = &device;
00037     fds[1].events = POLLIN;
00038 
00039     while (1) {
00040         // Block until either of the 2 ports is readable (or has an error)
00041         poll(fds, 2, -1);
00042 
00043         if (fds[0].revents) {
00044             copy_some(fds[1].fh, fds[0].fh);
00045         }
00046         if (fds[1].revents) {
00047             copy_some(fds[0].fh, fds[1].fh);
00048         }
00049     }
00050 }