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

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom 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.