|
| 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 10(RX), RX to pin 11(TX) |
| 17 | + * Second serial device's TX attached to digital pin 8(RX), RX to pin 9(TX) |
| 18 | +
|
| 19 | +
|
| 20 | + created 18 Apr. 2011 |
| 21 | + modified 19 March 2016 |
| 22 | + by Tom Igoe |
| 23 | + based on Mikal Hart's twoPortRXExample |
| 24 | +
|
| 25 | + This example code is in the public domain. |
| 26 | +
|
| 27 | + */ |
| 28 | + |
| 29 | +#include <SoftwareSerial.h> |
| 30 | +// software serial #1: RX = digital pin 10, TX = digital pin 11 |
| 31 | +SoftwareSerial portOne(10, 11); |
| 32 | + |
| 33 | +// software serial #2: RX = digital pin 8, TX = digital pin 9 |
| 34 | +// on the Mega, use other pins instead, since 8 and 9 don't work on the Mega |
| 35 | +SoftwareSerial portTwo(8, 9); |
| 36 | + |
| 37 | +void setup() { |
| 38 | + // Open serial communications and wait for port to open: |
| 39 | + Serial.begin(9600); |
| 40 | + while (!Serial) { |
| 41 | + ; // wait for serial port to connect. Needed for native USB port only |
| 42 | + } |
| 43 | + |
| 44 | + |
| 45 | + // Start each software serial port |
| 46 | + portOne.begin(9600); |
| 47 | + portTwo.begin(9600); |
| 48 | +} |
| 49 | + |
| 50 | +void loop() { |
| 51 | + // By default, the last intialized port is listening. |
| 52 | + // when you want to listen on a port, explicitly select it: |
| 53 | + portOne.listen(); |
| 54 | + Serial.println("Data from port one:"); |
| 55 | + // while there is data coming in, read it |
| 56 | + // and send to the hardware serial port: |
| 57 | + while (portOne.available() > 0) { |
| 58 | + char inByte = portOne.read(); |
| 59 | + Serial.write(inByte); |
| 60 | + } |
| 61 | + |
| 62 | + // blank line to separate data from the two ports: |
| 63 | + Serial.println(); |
| 64 | + |
| 65 | + // Now listen on the second port |
| 66 | + portTwo.listen(); |
| 67 | + // while there is data coming in, read it |
| 68 | + // and send to the hardware serial port: |
| 69 | + Serial.println("Data from port two:"); |
| 70 | + while (portTwo.available() > 0) { |
| 71 | + char inByte = portTwo.read(); |
| 72 | + Serial.write(inByte); |
| 73 | + } |
| 74 | + |
| 75 | + // blank line to separate data from the two ports: |
| 76 | + Serial.println(); |
| 77 | +} |
0 commit comments