[175] | 1 | /*
|
---|
| 2 | Software serial multple serial test
|
---|
| 3 |
|
---|
| 4 | Receives from the two software serial ports,
|
---|
| 5 | sends to the hardware serial port.
|
---|
| 6 |
|
---|
| 7 | In order to listen on a software port, you call port.listen().
|
---|
| 8 | When using two software serial ports, you have to switch ports
|
---|
| 9 | by listen()ing on each one in turn. Pick a logical time to switch
|
---|
| 10 | ports, like the end of an expected transmission, or when the
|
---|
| 11 | buffer is empty. This example switches ports when there is nothing
|
---|
| 12 | more to read from a port
|
---|
| 13 |
|
---|
| 14 | The circuit:
|
---|
| 15 | Two devices which communicate serially are needed.
|
---|
| 16 | * First serial device's TX attached to digital pin 9, RX to pin 11
|
---|
| 17 | * Second serial device's TX attached to digital pin 8, RX to pin 10
|
---|
| 18 |
|
---|
| 19 | This example code is in the public domain.
|
---|
| 20 |
|
---|
| 21 | */
|
---|
| 22 |
|
---|
| 23 | #include <SoftwareSerial.h>
|
---|
| 24 | // software serial #1: TX = digital pin 11, RX = digital pin 9
|
---|
| 25 | SoftwareSerial portOne(9, 11);
|
---|
| 26 |
|
---|
| 27 | // software serial #2: TX = digital pin 10, RX = digital pin 8
|
---|
| 28 | SoftwareSerial portTwo(8, 10);
|
---|
| 29 |
|
---|
| 30 | void setup()
|
---|
| 31 | {
|
---|
| 32 | // Open serial communications and wait for port to open:
|
---|
| 33 | SerialUSB.begin(115200);
|
---|
| 34 |
|
---|
| 35 | // Start each software serial port
|
---|
| 36 | portOne.begin(9600);
|
---|
| 37 | portTwo.begin(9600);
|
---|
| 38 | }
|
---|
| 39 |
|
---|
| 40 | void loop()
|
---|
| 41 | {
|
---|
| 42 | // By default, the last intialized port is listening.
|
---|
| 43 | // when you want to listen on a port, explicitly select it:
|
---|
| 44 | portOne.listen();
|
---|
| 45 |
|
---|
| 46 | SerialUSB.println("Data from port one:");
|
---|
| 47 | // while there is data coming in, read it
|
---|
| 48 | // and send to the hardware serial port:
|
---|
| 49 | while (portOne.available() > 0) {
|
---|
| 50 | char inByte = portOne.read();
|
---|
| 51 | SerialUSB.write(inByte);
|
---|
| 52 | }
|
---|
| 53 |
|
---|
| 54 | // blank line to separate data from the two ports:
|
---|
| 55 | SerialUSB.println("");
|
---|
| 56 |
|
---|
| 57 | // Now listen on the second port
|
---|
| 58 | portTwo.listen();
|
---|
| 59 | // while there is data coming in, read it
|
---|
| 60 | // and send to the hardware serial port:
|
---|
| 61 |
|
---|
| 62 | SerialUSB.println("Data from port two:");
|
---|
| 63 | while (portTwo.available() > 0) {
|
---|
| 64 | char inByte = portTwo.read();
|
---|
| 65 | SerialUSB.write(inByte);
|
---|
| 66 | }
|
---|
| 67 |
|
---|
| 68 | // blank line to separate data from the two ports:
|
---|
| 69 | SerialUSB.println();
|
---|
| 70 | }
|
---|
| 71 |
|
---|