mega_serial_spy.ino example

Testing sketch to run on an Arduino Mega to print all output from connected serial ports to the terminal.

Testing sketch to run on an Arduino Mega to print all output from connected serial ports to the terminal.

1/** =========================================================================
2 * @example{lineno} mega_serial_spy.ino
3 * @brief Testing sketch to run on an Arduino Mega to print all output from
4 * connected serial ports to the terminal.
5 *
6 * @m_examplenavigation{page_extra_helper_sketches,}
7 * ======================================================================= */
8
9#include <Arduino.h>
10
11void changeBauds(void) {
12 Serial.read();
13 for (uint8_t i = 1; i < 4; i++) {
14 Serial.print("Select a baud rate for Serial");
15 Serial.print(i);
16 Serial.println(" to monitor at:");
17 Serial.println("");
18 Serial.println("[1] - 9600");
19 Serial.println("[2] - 57600");
20 Serial.println("[3] - 115200");
21 Serial.println("[4] - 74880");
22 Serial.println("");
23 Serial.println(
24 "Enter you selection in the Serial Monitor and press <enter>");
25 Serial.println("");
26
27 String user_input = "";
28 int selection = 0;
29
30 // Wait for user feedback, then parse feedback one byte at a time
31 while ((Serial.peek() != 255) && !selection) {
32 char incoming = Serial.read();
33 if (isDigit(incoming)) {
34 // Append the current digit to the string placeholder
35 user_input += static_cast<char>(incoming);
36 }
37 // Parse the string on new-line
38 if (incoming == '\n') { selection = user_input.toInt(); }
39 delay(2);
40 }
41
42 uint32_t baud = 9600;
43
44 if (selection) {
45 switch (selection) {
46 case 1:
47 default: baud = 9600; break;
48 case 2: baud = 57600; break;
49 case 3: baud = 115200; break;
50 case 4: baud = 74880; break;
51 }
52 }
53
54 Serial.print("Starting Serial");
55 Serial.print(i);
56 Serial.print(" at ");
57 Serial.print(baud);
58 Serial.println(" baud.");
59
60 switch (i) {
61 case 1: Serial1.begin(baud); break;
62 case 2: Serial2.begin(baud); break;
63 case 3: Serial3.begin(baud); break;
64 }
65 }
66}
67
68
69void setup() {
70 Serial.begin(115200);
71
72 // Wait for the Serial Monitor to open
73 while (!Serial) {
74 // Delay required to avoid RTOS task switching problems
75 delay(1);
76 }
77
78 delay(500); // Short delay for cosmetic reasons
79 Serial.println("");
80 Serial.println("Serial port Spy\r\n");
81 Serial.println("-----------------------------------------------------------"
82 "--------------------");
83 changeBauds();
84}
85
86void loop() {
87 // From HW UART1 to USB
88 while (Serial1.available()) Serial.write(Serial1.read());
89 // From HW UART2 to USB
90 while (Serial2.available()) Serial.write(Serial2.read());
91 // From HW UART4 to USB
92 while (Serial3.available()) Serial.write(Serial3.read());
93
94 if (Serial.available()) changeBauds();
95}