2013-04-02

Multiplexing serial port NMEA sentences, and streaming to WiFi

In order to connect the GPS together with the VHF/AIS radio, and bringing the data to my iPad, I want to multiplex the incoming NMEA sentences to one single UDP stream.

The code below listens for data on the Arduino Mega's Serial1 and Serial2 ports (can easily be expanded to Serial + Serial3 as well). Incoming data is forwarded to the WiFly module, which streams the data using UDP. See previous posting for how to configure the WiFly module.


#include <WiFlyHQ.h>
#include <SoftwareSerial.h>

String _sentenceGPS;
String _sentenceVHF;
boolean _completedGPS;
boolean _completedVHF;
SoftwareSerial _wiflySerial(10, 11);
WiFly _wifly;

void setup()
{
  // Serial1: Baudrate=4800, Receive=GPS, Send=n/a
  _sentenceGPS.reserve(128);
  _completedGPS = false;
  Serial1.begin(4800);

  // Serial2: Baudrate=38400, Receive=AIS+DSC, Send=GPS
  _sentenceVHF.reserve(128);
  _completedVHF = false;
  Serial2.begin(38400);
  
  // WiFly module
  _wiflySerial.begin(38400);
  _wifly.begin(&_wiflySerial);
  _wifly.setIpProtocol(WIFLY_PROTOCOL_UDP);
}

void loop()
{
  RunMultiplexer();
}

void RunMultiplexer()
{
  char s[128];
  if (_completedGPS)
  {
    memset(s, 0, 128);
    _sentenceGPS.toCharArray(s, 128);
    _wifly.sendto(s, "255.255.255.255", 50000);
    Serial2.print(_sentenceGPS);  // Write GPS sentence to VHF
    _sentenceGPS = "";
    _completedGPS = false;
  }
  
  if (_completedVHF)
  {
    memset(s, 0, 128);
    _sentenceGPS.toCharArray(s, 128);
    _wifly.sendto(s, "255.255.255.255", 50);
    _sentenceVHF = "";
    _completedVHF = false;
  }
}

void serialEvent1()
{
  if (Serial1.available())
  {
    char c = Serial1.read();
    _sentenceGPS += c;
    if (c == '\n')
    {
      _completedGPS = true;
    }
  }
}

void serialEvent2()
{
  if (Serial2.available())
  {
    char c = Serial2.read();
    _sentenceVHF += c;
    if (c == '\n')
    {
      _completedVHF = true;
    }
  }
}


Right now the incoming GPS data on Serial1 is forwarded to the outgoing Serial2 port. I will add parsers and more logic to this - stay tuned! :-)

1 comment:

  1. Hi, that is great idea, I was looking to this knid of work, would you say what app you are using at your iPad? I have just finished working with circuit board that converting (AIS audio signal) from VHF radio to Serial (RS232), so I would like to multiplex that to GPS & Wind info & or maybe more... like you bering the data to my iPad & plotter.
    Keep the good work
    Reza

    ReplyDelete