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

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »

Price Scanner via MacPrices.net

Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more

Jobs Board

Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.