Skip to content

Commit dd81220

Browse files
committed
Add code snippet for UnbufferedSerial and BufferedSerial API documentation
1 parent e1d5095 commit dd81220

File tree

3 files changed

+91
-0
lines changed

3 files changed

+91
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#include "mbed.h"
2+
3+
4+
// Maximum number of element the application buffer can contain
5+
#define MAXIMUM_BUFFER_SIZE 32
6+
7+
8+
// Create a DigitalOutput object to toggle an LED whenever data is received.
9+
static DigitalOut led(LED1);
10+
11+
// Create a new UARTSerial object with a default baud rate.
12+
static BufferedSerial serial_port(USBTX, USBRX);
13+
14+
15+
int main(void) {
16+
// Set desired properties (9600-8-N-1).
17+
serial_port.set_baud(9600);
18+
serial_port.set_format(
19+
/* bits */ 8,
20+
/* parity */ BufferedSerial::None,
21+
/* stop bit */ 1
22+
);
23+
24+
// Application buffer to receive the data
25+
char buf[MAXIMUM_BUFFER_SIZE] = {0};
26+
27+
while (1) {
28+
if (uint32_t num = serial_port.read(buf, sizeof(buf))) {
29+
// Toggle the LED.
30+
led = !led;
31+
32+
// Echo the input back to the terminal.
33+
serial_port.write(buf, num);
34+
}
35+
}
36+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#include "mbed.h"
2+
3+
// Create a new UARTSerial object with a default baud rate.
4+
static BufferedSerial serial_port(USBTX, USBRX, 9600);
5+
6+
7+
FileHandle *mbed::mbed_override_console(int fd) {
8+
return &serial_port;
9+
}
10+
11+
12+
int main(void) {
13+
// print to the console using the `serial_port` object.
14+
printf(
15+
"Mbed OS version %d.%d.%d\n",
16+
MBED_MAJOR_VERSION,
17+
MBED_MINOR_VERSION,
18+
MBED_PATCH_VERSION
19+
);
20+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include "mbed.h"
2+
3+
4+
// Create a DigitalOutput object to toggle an LED whenever data is received.
5+
static DigitalOut led(LED1);
6+
7+
// Create a new UnbufferedSerial object with a default baud rate.
8+
static UnbufferedSerial serial_port(USBTX, USBRX);
9+
10+
void on_rx_interrupt()
11+
{
12+
char c;
13+
14+
// Toggle the LED.
15+
led = !led;
16+
17+
// Read the data to clear the receive interrupt.
18+
if (serial_port.read(&c, 1)) {
19+
// Echo the input back to the terminal.
20+
serial_port.write(&c, 1);
21+
}
22+
}
23+
24+
int main(void) {
25+
// Set desired properties (9600-8-N-1).
26+
serial_port.baud(9600);
27+
serial_port.format(
28+
/* bits */ 8,
29+
/* parity */ SerialBase::None,
30+
/* stop bit */ 1
31+
);
32+
33+
// Register a callback to process a Rx (receive) interrupt.
34+
serial_port.attach(&on_rx_interrupt, SerialBase::RxIrq);
35+
}

0 commit comments

Comments
 (0)