Solved

Serial Programming

Posted on 2000-05-12
2
223 Views
Last Modified: 2013-12-26
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...
0
Comment
Question by:Snowlcok
2 Comments
 
LVL 10

Expert Comment

by:rbr
ID: 2816829
Which language?
0
 
LVL 4

Accepted Solution

by:
Alex Curylo earned 50 total points
ID: 2817721
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

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
bobThere java chalenge 45 85
Smart Camera scanning and reading information 3 86
sumHeights  challenge 17 61
noX challenge 17 76
Introduction: Finishing the grid – keyboard support for arrow keys to manoeuvre, entering the numbers.  The PreTranslateMessage function is to be used to intercept and respond to keyboard events. Continuing from the fourth article about sudoku. …
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now