Sending Data to Two Serial Devices at the Same Time

Posted by Unknown on Monday, August 04, 2014 with No comments
You want to send data to a serial device such as a serial LCD, but you are already using
the built-in serial port to communicate with your computer.

On a Mega this is not a problem, as it has four hardware serial ports; just create two
serial objects and use one for the LCD and one for the computer:

void setup() {
// initialize two serial ports on a Mega
Serial.begin(9600); // primary serial port
Serial1.begin(9600); // Mega can also use Serial1 through Serial3
}

On a standard Arduino board (such as the Uno or Duemilanove) that only has one
hardware serial port, you will need to create an emulated or “soft” serial port.
You can use the distributed SoftwareSerial library for sending data to multiple devices.


Select two available digital pins, one each for transmit and receive, and connect your
serial device to them. It is convenient to use the hardware serial port for communication
with the computer because this has a USB adapter on the board. Connect the device’s
transmit line to the receive pin and the receive line to the transmit pin.Connecting a serial device to a “soft” serial port
In your sketch, create a Software Serial object and tell it which pins you chose as your
emulated serial port.
 In this example, we’re creating an object named  serial_lcd, which
we instruct to use pins 2 and 3:
/*
* SoftwareSerialOutput sketch
* Output data to a software serial port
*/
#include <SoftwareSerial.h>
const int rxpin = 2; // pin used to receive (not used in this version)
const int txpin = 3; // pin used to send to LCD
SoftwareSerial serial_lcd(rxpin, txpin); // new serial port on pins 2 and 3
void setup()
{
Serial.begin(9600); // 9600 baud for the built-in serial port
serial_lcd.begin(9600); //initialize the software serial port also for 9600
}
int number = 0;
void loop()
{
serial_lcd.print("The number is "); // send text to the LCD
serial_lcd.println(number); // print the number on the LCD
Serial.print("The number is ");
Serial.println(number); // print the number on the PC console
delay(500); // delay half second between numbers
number++; // to the next number
}
If you are using Arduino versions prior to 1.0, download the NewSoftSerial  library  and  replace  references  to  SoftwareSerial  with  NewSoftSerial:
// NewSoftSerial version
#include <NewSoftSerial.h>
const int rxpin = 2; // pin used to receive from LCD
const int txpin = 3; // pin used to send to LCD
NewSoftSerial serial_lcd(rxpin, txpin); // new serial port on pins 2 + 3
This sketch assumes that a serial LCD has been connected to pin 3 as shown in Figure 4-6, and that a serial console is connected to the built-in port. The loop will repeatedly display the same message on each:
The number is 0
The number is 1
Categories: