Serial Programming

Hi, I am new to the Mac world,
and I need to write a small
program that sends simple strings
to an external device through
serial port.

Can someone show me how to initialize, and send / receive
string to the device?

a sample code would be very appreciated.

And no, this is not a homework.
this is for a research project,
but now that we are using the mac
instead of intel, I am clueless
as to how to communicate with
the serial...
SnowlcokAsked:
Who is Participating?
 
Alex CuryloConnect With a Mentor Commented:
This should be more or less easily adaptable to your needs.

// CGCConnection.h
//
// Serial connection class for Ball GCs

#pragma once

class CGCConnection
{
public:
                        CGCConnection();
      virtual            ~CGCConnection();
      
      bool                        WaitForChar(char inChar);
      bool                        WaitForData(void* ioBuffer, long length);
      void                        SendChar(char theChar, long inDelay = 0);
      void                        SendData(char* theData, Int32 theLength);
      bool                        OpenConnection(StringPtr inPort);
      void                        CloseConnection();
      
      UInt32            GetLastContact() { return mLastContact; }
      void            ResetLastContact() { mLastContact = ::TickCount(); }
      
protected:
      short                        mInRefNum, mOutRefNum;
      
      enum { size_InputBuffer = 1024 };
      Ptr                              mInputBuffer;

      UInt32                        mLastContact;
      
};

// CGCConnection.cp
//
// Serial connection class for Ball GCs

#include <Serial.h>
#include <CommResources.h>
#include <CRMSerialDevices.h>

#include "CGCConnection.h"
#include "LAlert.h"
#include "LogbookResources.h"

CGCConnection::CGCConnection()
{
      mInRefNum = mOutRefNum = 0;
      mInputBuffer = nil;
}

CGCConnection::~CGCConnection()
{
      CloseConnection();
}

bool CGCConnection::OpenConnection(StringPtr inPort)
{
      try
      {
            Str255 inputDriver;
            Str255 outputDriver;
            
            CRMRec            c;
            CRMRecPtr      cPtr = &c;
            CRMSerialPtr      serialPtr;
            
            // walk the serial device list until we find the entry for the current port
            c.crmDeviceType = crmSerialDevice;
            c.crmDeviceID   = 0;
            while (cPtr != nil) {
                  cPtr = (CRMRecPtr)::CRMSearch((CRMRecPtr)cPtr);
                  if (cPtr) {
                        serialPtr = (CRMSerialPtr)cPtr->crmAttributes;
                        if (::EqualString(inPort, *(serialPtr->name),false,false) ){
                              LString::CopyPStr(*(serialPtr->inputDriverName), inputDriver);
                              LString::CopyPStr(*(serialPtr->outputDriverName), outputDriver);
                              break;
                        }
                        c.crmDeviceID = cPtr->crmDeviceID;
                  }
            }

            ThrowIfOSErr_(::OpenDriver(outputDriver, &mOutRefNum));
            ThrowIfOSErr_(::OpenDriver(inputDriver, &mInRefNum));

            short portConfig = baud4800 + data8 + stop10 + noParity;
            ThrowIfOSErr_(::SerReset(mOutRefNum, portConfig));
            ThrowIfOSErr_(::SerReset(mInRefNum, portConfig)); // supposedly redundant
            
            mInputBuffer = ::NewPtr(size_InputBuffer);
            ThrowIfNil_(mInputBuffer);
            ThrowIfOSErr_(::SerSetBuf(mInRefNum, mInputBuffer, size_InputBuffer));
      }
      catch(ExceptionCode inErr)
      {
            switch(inErr)
            {
                  case portInUse:
                        LAlert::StopAlert(STRx_Errors, str_PortInUse);
                        break;
                  default:
                        LAlert::UnexpectedError();
                        break;
            }
            return false;
      }
      catch(...)
      {
            LAlert::UnexpectedError();
            return false;
      }

      return true;
}

void CGCConnection::CloseConnection()
{
      if (mInRefNum)
      {
            ::CloseDriver(mInRefNum);
            mInRefNum = 0;
      }
      if (mOutRefNum)
      {
            ::CloseDriver(mOutRefNum);
            mOutRefNum = 0;
      }
      if (mInputBuffer)
      {
            ::DisposePtr(mInputBuffer);
            mInputBuffer = nil;
      }
}

bool
CGCConnection::WaitForData(void* ioBuffer, long length)
{
      try
      {
            long dataWaiting = 0;
            ThrowIfOSErr_(::SerGetBuf(mInRefNum, &dataWaiting));
            if (dataWaiting >= length)
            {
                  dataWaiting = length;
                  ThrowIfOSErr_(::FSRead(mInRefNum, &dataWaiting, ioBuffer));
                  mLastContact = ::TickCount();
                  return true;
            }
      }
      catch(...)
      {
            LAlert::UnexpectedError();
            throw -1;
      }
      return false;
}

bool
CGCConnection::WaitForChar(char inChar)
{
      try
      {
            long dataWaiting = 0;
            ThrowIfOSErr_(::SerGetBuf(mInRefNum, &dataWaiting));
            if (dataWaiting)
            {
                  dataWaiting = 1;
                  ThrowIfOSErr_(::FSRead(mInRefNum, &dataWaiting, &inChar));
                  mLastContact = ::TickCount();
                  return true;
            }
      }
      catch(...)
      {
            LAlert::UnexpectedError();
            throw -1;
      }
      return false;
}


void
CGCConnection::SendChar(char inChar, long inDelay)
{
      SendData(&inChar, 1);

      // note this is ticks. Windows code is in milliseconds.
      unsigned long delayUntil;
      if (inDelay)
            ::Delay(inDelay, &delayUntil);
}

void
CGCConnection::SendData(char * theData, Int32 theLength)
{
      try
      {
            ThrowIfOSErr_(::FSWrite(mOutRefNum, &theLength, theData));
      }
      catch(...)
      {
            LAlert::UnexpectedError();
      }
}

The other piece you need is how to get the available port names. Do that with something like this.

void
CLogbookApp::InitSerialPortMenu()
{
      // Get list of serial ports from CTB
      
      LMenu *portMenu = LMenuBar::GetCurrentMenuBar()->FetchMenu(menu_Port);
      ThrowIfNil_(portMenu);
      mPortMenuH = portMenu->GetMacMenuH();
      Int16 theCount = ::CountMItems(mPortMenuH);                                                      
      for(Int16 item = theCount; item > 0; item--)
            portMenu->RemoveItem(item);
      
      // Fill the menu with the names of the available serial ports
      CRMRec            c;
      CRMRecPtr      cPtr = &c;
      CRMSerialPtr      serialPtr;
      
      // init the CoomToolbox
      InitCRM();
      
      c.crmDeviceType = crmSerialDevice;
      c.crmDeviceID   = 0;
      while (cPtr != nil)
            {
            cPtr = (CRMRecPtr)CRMSearch((CRMRecPtr)cPtr);
            if (cPtr) {
                  serialPtr = (CRMSerialPtr)cPtr->crmAttributes;
                  
                  portMenu->InsertCommand(nameStr, cmd_UseMenuItem, ::CountMItems(mPortMenuH));
                  
                  c.crmDeviceID = cPtr->crmDeviceID;
                  
                  // let's never have an unintialized port
                  if (!sPreferences.GetPrefs().portName[0])
                        LString::CopyPStr(nameStr, sPreferences.GetPrefs().portName);
            }
      }
}
0
 
rbrCommented:
Which language?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.