?
Solved

Serial Programming

Posted on 2000-05-12
2
Medium Priority
?
233 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 10

Expert Comment

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

Accepted Solution

by:
Alex Curylo earned 150 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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article, I'll describe -- and show pictures of -- some of the significant additions that have been made available to programmers in the MFC Feature Pack for Visual C++ 2008.  These same feature are in the MFC libraries that come with Visual …
This is to be the first in a series of articles demonstrating the development of a complete windows based application using the MFC classes.  I’ll try to keep each article focused on one (or a couple) of the tasks that one may meet.   Introductio…
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.
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

650 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