Help: how to output to a port such as a RS232?

Scott J Brickner sjb at piobe.Berkeley.EDU
Wed Jun 12 07:04:57 AEST 1991


In article <1991Jun11.135431.22955 at udecc.engr.udayton.edu>, Jinghong Li writes:
> Help needed:  would someone tell me how to send output
> to a port such as a RS232?  Any sepcial commands? 
> If the address of the port is known, hwo to declare 
> it as a FILE pointer? ...

I assume you are working under some sort of monitor rather than a real
operating system.  If you have an operating system, you would call open()
or fopen() with an appropriate device name (e.g. "/dev/tty0" under UNIX, or
"COM1:" under DOS).  If you don't, things get a little more tricky.  You no
longer can use file pointers or file descriptors for I/O, you have to deal
with the I/O control registers directly. A (mythical) example of such code
might be:

    putsRS232( unsigned char *s)
    {
	struct regs232 {
	    struct {
		unsigned char busy:1;
		unsigned char dummy:6;
		unsigned char interrupt:1;
		unsigned char ienb:1;
	    } control;
	    unsigned char data;
	} *r = ( struct regs232 *) 0xffff0010;

	r->control.ienb = 0;
	while ( *s++)
	{
	    while ( r->control.busy)
		/* busy wait loop - do nothing */ ;
	    r->data = *s;
	}
    }

The above assumes that the RS232 hardware is memory mapped to address
0xffff010 (1 byte control register) and 0xffff011 (1 byte data register),
that no data may be written until the busy bit (bit 0 in the control
register) is off, and that bytes are output when written to the data
register.  I have also included some stuff to make sure interrupts are off
(by turning of the ienb bit (bit 7 in the control register)).  While this
may not actually conform to reality in any system, it isn't too far off
from some common configurations (PDP architecture), so you should be able
to get a feel for what is needed.  Other code would use the puts232
function as follows:

    puts( "Hello, world\n");

If you really want to use interrupts, and so forth, you're opening a much
larger can of worms than I'd like to try to discuss here.

Note that the above code uses some machine dependent constructs (ordering
of bit fields within a byte, minimum size of fields, etc), but since I made
up the hardware, and it IS pretty machine dependent how you do output
directly to the hardware, I guess I can make up the machine dependencies of
the compiler, too, now can't I?

Scott J Brickner
(P.S. Please don't flame the coding style - I don't particularly care what
your's is or in what ways you consider it superior to mine... Mine works
just fine for me.)



More information about the Comp.lang.c mailing list