Solved

Serial Programming

Posted on 2000-05-12
2
231 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 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Introduction: Ownerdraw of the grid button.  A singleton class implentation and usage. Continuing from the fifth article about sudoku.   Open the project in visual studio. Go to the class view – CGridButton should be visible as a class.  R…
Introduction: The undo support, implementing a stack. Continuing from the eigth article about sudoku.   We need a mechanism to keep track of the digits entered so as to implement an undo mechanism.  This should be a ‘Last In First Out’ collec…
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.
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…

707 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