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

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 »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »

Price Scanner via MacPrices.net

You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more

Jobs Board

IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
Top Secret *Apple* System Admin - Insight G...
Job Description Day to Day: * Configure and maintain the client's Apple Device Management (ADM) solution. The current solution is JAMF supporting 250-500 end points, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.