TweetFollow Us on Twitter

Serial Port Demo
Volume Number:4
Issue Number:6
Column Tag:Pascal Procedures

Serial Port Demo

By Tom Scheiderich, Fullerton, CA

Just try to find out anything about how to talk to the Macs serial ports. I have looked in about 10-15 books and they all seem to forget the these devices exist. You can see how to write to the screen, the disk, the printer, the system clock etc. What happened to the serial ports!!! They aren’t so mysterious, as you will see. The only place I found any information about them is in Inside Macintosh. Anyone who has read Inside Macintosh knows that it is very difficult to follow as a tutorial, even by professional programmers. In many cases, a good example program, along with some discussion of the subject, will better help most programmers grasp the new techniques. “A Picture is worth a Thousand Words”!!! I learned about serial ports from a very basic terminal emulator. I just played with it and talked to other people about it. I will try to impart what I have learned to those interested. The sample program is derived from a Data Analyser program I wrote which can be used to examine data going back and forth between two serial devices. For example, from between a printer and a computer or a modem and a computer. Our sample program displays one window for each serial port, and sends data typed at the keyboard out one port and in the other, where it is displayed in the port’s window. This completely demonstrates both reading and writing to the Macintosh serial ports.

A serial port is one of the computer’s means to talk to the outside world in which the data is sent one bit at a time to some device such as a modem or printer. The Mac has 2 such ports at its disposal. Each port has two default buffers of 64 characters, an input and an output buffer. It seems that each buffer is set up in a circular fashion.

Fig. 1 Output of our sample Serial Port Program

General Circular Buffer Procedure

A circular buffer works logically as shown in the graphic. Logically there is no end to the buffer. It just keeps going around in a circle.

What actually happens in this type of buffer is that as a byte is received, it is put in the next position in the buffer. If the end of the buffer is reached, the byte is put at the start of the buffer overwriting whatever byte was there before. The users extracts these bytes from this buffer and put them into a work area (a character, byte or array). As each byte is received, a check must be made to see if the number of bytes in the buffer match the maximum number of bytes allowed in the buffer. Since we don’t want to over-write these bytes, the program must then tell the device (modem, for example) not to send any more data until later. The device will then “go to sleep” until requested to continue. This is called handshaking. There is no shifting of bytes as the data is read from and written to the buffer. The bytes will stay in the buffer as is, until over-written by new data.

In the following example, we will assume that data is coming from a modem and is sending the word “TESTING”. We have already received “TEST” and we are just going to read our first byte from the buffer. There are four control variables needed to handle the buffer.

1. Buffer Size - This is the total number of bytes available in our buffer.

2. Get Byte - The next byte position in the buffer to read.

3. Put Byte - The next byte position in the buffer available to put a byte.

4. Byte Count - The number of bytes available in the buffer to read. This will be (Put Byte - Get Byte). If < 0 then add Buffer Size.

At this point there are 4 bytes in the Buffer. The next byte we are going to read is a “T” which is in byte #1. The next byte coming from the modem will go into byte #5.

After the byte is taken from the circular buffer and put into a buffer specified by the program, the Byte Count will be set to 3, which says there are now three bytes in the buffer to be read. The next byte to be read is in the 2nd byte position. This will be the letter “E”. You will notice that nothing has happened to the “T” in position 1.

After the byte is put into the circular buffer, the Byte Count is then set to 4, which says there are now four bytes in the buffer to be read. The next byte read from the modem will be put into the 6th byte position.

Here we are also putting a byte into the buffer but have run out of room. The next position would have been 65. Since this is greater than the Buffer Size, we now wrap around and put the byte in byte position 1, over-writing the “T”. Also, you will notice that the Byte Count equals the Buffer size. We cannot accept any more bytes until some bytes are taken out of the buffer, so we must perform some sort of handshaking to stop the modem from sending any more data. In the real world, this would happen before the buffer was full. The data could be coming so fast that by the time the modem has found out it is supposed to stop, it may have sent 20 more bytes.

Macintosh Serial Ports

Now we will see how this all applies to the Mac, which of course is our only reason for living.

The Mac has two serial ports to choose from. Each of these ports has an input buffer and an output buffer. These are “our” circular buffers. Each buffer has a default size of 64 bytes. This can be changed to whatever size you want by a call to SerSetBuf. You don’t have to worry about the control variables from our previous discussion of the circular buffers as these are handled internally by the Serial Drivers. The control variables were just to demonstrate how a circular buffer is handled. You may, however, want to know how many bytes are in the buffer at any one time. This is accomplished by a call to SerGetBuf. If the count returned is not equal to 0, then a call to FSRead is executed. FSRead will take the number of bytes requested out of the buffer, puts them into a buffer specified by the program and updates the buffers control words. The program can then do what it wishes with the data. For example, if running a terminal emulator, the bytes received might be text and can now be displayed to the screen. If receiving a file, the bytes might now be written to the disk.

The sample program was written in Lightspeed Pascal. You should be able to see that dealing with the serial ports is very simple and not a mystery at all. The whole serial flow can be broken down to the following steps:

1. Open and set up the Serial Port.

2. Get any bytes that might be in the input buffer and deal with the data.

3. Check if any keys have been pressed and write out the serial port

4. Go back to # 2 and repeat.

The actual flow is summarized here in the flowchart shown at the end of the article.

In the example program, characters entered by the keyboard are written out one serial port and read into the other serial port and displayed on one of the two screens.

Before we start looking at the program some important Serial port variables need to be understood:

1. inBuffPtr - this is the 2k circular buffer that we are going to replace the default 64k buffer with. We set up the size and pointer to it (NewPtr) and then pass the pointer to the driver routine by way of SerSetBuf . We don’t deal with it anymore from this point on. All of our dealings will be with inRefNum and outRefNum

2. filterBuffPtr - the data returned from FSRead is put into this buffer. Since we will only be reading one character at a time, we only set up the buffer as one byte long. If we were going to read more than one byte from the buffer, you must set it up to the maximum number of bytes you might read. You may want to set the size the same as inBuffPtr . Unlike the circular buffers, the data being transfered will be put in the buffer starting from the first byte and continuing until all the bytes requested are transferred.

3. inRefNum - this is the input channel (reference) number. This number will be either a -6 (modem) or -8 (printer). All reading from the serial port will be done by referencing this number. It gets set up in RAMSDopen.

4. outRefNum - this is the output channel (reference) number. This number will be either a -7 (modem) or -9 (printer). All writing to the serial port will be done by referencing this number. It gets set up in RAMSDopen.

Each of these variables is set up as either “A” variables for the modem ports or “B” variables for the printer ports. For example, there is an inRefNumA for the modem and an inRefNumB for the printer. These are needed in our routine since we will be reading and writing to both of the ports.

To change the default settings (9600 baud, 8 data bits, 2 stop bits and no parity), set SerConfig, which is an integer that has its bits set for the appropriate parameters and passed along with the reference number to SerReset.

Handshaking is needed to prevent data overruns in the circular buffers. If no handshaking or the wrong handshaking is defined, you could get this overrun. Many of you have seen this with your printers when you are struggling to get the correct parity and stop bits set up. You will see a lot of garbage on your paper until you get it correct. This is caused many times because some data is getting lost when the printer has told your computer to stop sending, but because of incorrect settings, the computer kept sending data anyway and some of it was lost.

You will need to set up a record of control bytes to tell the Mac what type of handshaking you want it to do and call SerHShake while passing this record. The record contains:

1. fXOn - XOn/XOff output buffer flow control flag. If this is nonzero, then XOn/XOff flow control is enabled for the output buffer.

2. fCTS - If nonzero, then hardware flow control is enabled. The handshaking will then be controlled by lines 4 and 5 of the serial port.

3. xOn - What XOn character to use (usually a control-Q).

4. xOff - What XOff character to use ( usually a control-S).

5. errs - Tells the driver which type of errors cause input request to be aborted (parity, hardware overruns, or framing errors).

6. evts - This byte tells whether changes in CTS or Break status will cause the driver to post device driver events. This option is discouraged because interrupts are disabled for a long time while events are being posted

7. fInX - XOn/XOff input buffer flow control flag. If this is nonzero then XOn/XOff flow control is enabled for the input buffer.

The type of handshaking we use here doesn’t matter because everytime we send a character we also read it, so there is no way to get an overrun. But I have it set up as XOn/XOff for the input buffer only, using a control-S and a control-Q as our XOn/XOff characters for demonstration purposes.

Before starting the program you will need to a special cable. They are very easy to build. Since we are dealing with XOn/XOff, we need only 3 wires; the transmit, receive and ground wires. We are building a null modem cable which is just a cable which reverses the transmit and receive lines. When we are transmitting out the modem port, we will be receiving through the printer port and vice versa.

Pin Assignments on the Serial Ports

Following are the cable setups needed for the included program. To use the DB-9’s, if you are using a Mac Plus, Mac SE or a Mac II, you will need to purchase two - DB-9 to mini-8 conversion cables. The DB-9 connectors are easier to deal with than the mini-8 connecters and both DB-9 connectors are male.

To wire the cable, take the two male DB-9 connectors and wire them as shown in the figure below. Wire pin 3 to pin 3, ground. Wire pin 5 on one to pin 9 on the other for transmit. And finally, wire pin 9 on one to pin 5 on the other for receive. Then plug each male DB-9 connector into an Apple mini-8 to DB-9 cable and plug the two mini-8 connectors into the modem and printer ports on the back of the Mac. The Apple cables are available at Apple dealers to convert the mini-8 serial ports to the old style DB-9 connector devices used by the Mac 128 and Mac 512 computers. If you are a wiz, you can try to make a mini-8 cable instead, but we don’t recommend it.

The first thing that is done in our program is to open the serial ports which is done in the Init_Serial routine. We are using the RAM serial driver. Note that AppleTalk must be turned off at the chooser in order for this to work. All buffers and pointers are set up here. Next we will set up the two windows shown in figure 1.

The window selected is the port the data will be transferred out of and the other window is the port that will be doing the receiving. The non-selected window will be the one we display the text on.

Now we will just go into our normal “mainloop” routine. The first thing we will do is check for any bytes in the serial buffer (Get_comm_input). SerGetBuf is called to see if there are any bytes in our serial buffer. If there are, we will call FSRead (from GetChar) to get a character out of the buffer. Before writing to the window we need to call SetPort to select the correct window. If PortA is true, we are writing out the modem port and are displaying on window B, so we would then call SetPort(windowB) to select the second window and draw the character onto the screen (Put_Char).

Last of all is to see if a key was pressed. If so, we need to write the character out the output port (Handle_keys). A call would be made to FSWrite to transfer the character.

The only other routine of interest would be RSerBuf which is called to reset the buffers and pointers and to reverse the input and output ports. This is done whenever a new window is selected or at the start of the program. Clicking in the content region of the unselected window, then reverses which window and port is doing the output and input of our characters typed on the keyboard.

One last thing. We are using the RAM Serial Driver for our program, but we could just as easily have used the ROM Serial Driver. The main problem is that the ROM Driver doesn’t support XOn/XOff, so if this is necessary use the RAM Driver. If the ROM driver is needed then all that need be done is:

Replace

 errl:=RAMSDOpen(sPortA)

With

 errI := OpenDriver(‘.Ain’, inRefNum);
                    errI := OpenDriver(‘.Aout’, outRefNum);

You need to explicitly open the input and the output Drivers.

Wiring our null modem cable for port to port communications

 
AAPL
$102.50
Apple Inc.
+0.25
MSFT
$45.43
Microsoft Corpora
+0.55
GOOG
$571.60
Google Inc.
+2.40

MacTech Search:
Community Search:

Software Updates via MacUpdate

VueScan 9.4.41 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more
Cloud 3.0.0 - File sharing from your men...
Cloud is simple file sharing for the Mac. Drag a file from your Mac to the CloudApp icon in the menubar and we take care of the rest. A link to the file will automatically be copied to your clipboard... Read more
LibreOffice 4.3.1.2 - Free Open Source o...
LibreOffice is an office suite (word processor, spreadsheet, presentations, drawing tool) compatible with other major office suites. The Document Foundation is coordinating development and... Read more
SlingPlayer Plugin 3.3.20.505 - Browser...
SlingPlayer is the screen interface software that works hand-in-hand with the hardware inside the Slingbox to make your TV viewing experience just like that at home. It features an array of... Read more
Get Lyrical 3.8 - Auto-magically adds ly...
Get Lyrical auto-magically add lyrics to songs in iTunes. You can choose either a selection of tracks, or the current track. Or turn on "Active Tagging" to get lyrics for songs as you play them.... Read more
Viber 4.2.2 - Send messages and make cal...
Viber lets you send free messages and make free calls to other Viber users, on any device and network, in any country! Viber syncs your contacts, messages and call history with your mobile device,... Read more
Cocktail 7.6 - General maintenance and o...
Cocktail is a general purpose utility for OS X that lets you clean, repair and optimize your Mac. It is a powerful digital toolset that helps hundreds of thousands of Mac users around the world get... Read more
LaunchBar 6.1 - Powerful file/URL/email...
LaunchBar is an award-winning productivity utility that offers an amazingly intuitive and efficient way to search and access any kind of information stored on your computer or on the Web. It provides... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
BBEdit 10.5.12 - Powerful text and HTML...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more

Latest Forum Discussions

See All

This Week at 148Apps: August 25-29, 2014
Shiny Happy App Reviews   | Read more »
Qube Kingdom – Tips, Tricks, Strategies,...
Qube Kingdom is a tower defense game from DeNA. You rally your troops – magicians, archers, knights, barbarians, and others – and fight against an evil menace looking to dominate your kingdom of tiny squares. Planning a war isn’t easy, so here are a... | Read more »
Qube Kingdom Review
Qube Kingdom Review By Nadia Oxford on August 29th, 2014 Our Rating: :: KIND OF A SQUARE KINGDOMUniversal App - Designed for iPhone and iPad Qube Kingdom has cute visuals, but it’s a pretty basic tower defense game at heart.   | Read more »
Fire in the Hole Review
Fire in the Hole Review By Rob Thomas on August 29th, 2014 Our Rating: :: WALK THE PLANKUniversal App - Designed for iPhone and iPad Seafoam’s Fire in the Hole looks like a bright, 8-bit throwback, but there’s not enough booty to... | Read more »
Alien Creeps TD is Now Available Worldwi...
Alien Creeps TD is Now Available Worldwide Posted by Ellis Spice on August 29th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Dodo Master Review
Dodo Master Review By Jordan Minor on August 29th, 2014 Our Rating: :: NEST EGGiPad Only App - Designed for the iPad Dodo Master is tough but fair, and that’s what makes it a joy to play.   | Read more »
Motorsport Manager Review
Motorsport Manager Review By Lee Hamlet on August 29th, 2014 Our Rating: :: MARVELOUS MANAGEMENTUniversal App - Designed for iPhone and iPad Despite its depth and sense of tactical freedom, Motorsport Manager is one of the most... | Read more »
Motorsport Manager – Beginner Tips, Tric...
The world of Motorsport management can be an unforgiving and merciless one, so to help with some of the stress that comes with running a successful race team, here are a few hints and tips to leave your opponents in the dust. | Read more »
CalPal Update Brings the App to 2.0, Add...
CalPal Update Brings the App to 2.0, Adds Lots of New Stuff Posted by Ellis Spice on August 29th, 2014 [ permalink ] | Read more »
Baseball Battle Review
Baseball Battle Review By Jennifer Allen on August 29th, 2014 Our Rating: :: SIMPLE HITTINGUniversal App - Designed for iPhone and iPad Simple and cute, Baseball Battle is a fairly fun baseball game for those looking for something... | Read more »

Price Scanner via MacPrices.net

Labor Day Weekend MacBook Pro sale; 15-inch m...
B&H Photo has the new 2014 15″ Retina MacBook Pros on sale for up to $125 off MSRP. Shipping is free, and B&H charges NY sales tax only. They’ll also include free copies of Parallels Desktop... Read more
Labor Day Weekend iPad mini sale; $50 to $100...
Best Buy has the iPad mini with Retina Display (WiFi models) on sale for $50 off MSRP on their online store for Labor Day Weekend. Choose free shipping or free local store pick up. Price is for... Read more
13-inch 1.4GHz MacBook Air on sale for $899,...
Adorama has the new 2014 13″ 1.4GHz/128GB MacBook Air on sale for $899.99 including free shipping plus NY & NJ tax only. Their price is $100 off MSRP. Read more
It’s Official: Apple Issues Invitations To Se...
Apple has issued one of its characteristically cryptic press invitations for a special event to be held at the Flint Center for the Performing Arts in hometown Cupertino on Sept. 9, 2014 at 10:00 am... Read more
Tablet Shipments To See First On-year Decline...
TrendForce analyst Caroline Chen notes that when the iPad launched in 2010, it was an instant hit and spurred a tablet PC revolution, with tablets so popular that that notebook PC sales stagnated and... Read more
SOBERLINK Releases Apple iOS Compatible Handh...
Cypress, California based SOBERLINK, Inc., creator of the first handheld Breathalyzer designed to improve recovery outcomes, continues to show prominence in the mobile alcohol monitoring space with... Read more
New 21″ 1.4GHz iMac on sale again for $999, s...
Best Buy has the new 21″ 1.4GHz iMac on sale for $999.99 on their online store. Their price is $100 off MSRP. Choose free shipping or free local store pick up. Price is for online orders only, in-... Read more
Smartphone Outlook Remains Strong for 2014, U...
According to a new mobile phone forecast from the International Data Corporation (IDC) Worldwide Quarterly Mobile Phone Tracker, more than 1.25 billion smartphones will be shipped worldwide in 2014,... Read more
Save up to $60 with Apple refurbished iPod to...
The Apple Store has Apple Certified Refurbished 5th generation iPod touches available starting at $149. Apple’s one-year warranty is included with each model, and shipping is free. Many, but not all... Read more
12-Inch MacBook Air Coming in 4Q14 or 2015 –...
Digitimes’ Aaron Lee and Joseph Tsai report that according to Taiwan-based upstream supply chain insiders, Apple plans to launch a thinner MacBook model either at year end 2014 or in 2015, and that... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.