serial Buffer Peek

One item that is missing from the serial library is the ability to get the most recent character received. This is useful, for example, when waiting for a carriage return at the end of a command.

I wrote my own routine to do so; here it is:

Cheers!
Daniel W. Rickey
CancerCare Manitoba

/**** MyRS232.LIB ****/

/*** Beginheader cBuf_LastPeek /
int cBuf_LastPeek(char buf);
/
* endheader */

/* _START FUNCTION DESCRIPTION ********************************************
cBuf_LastPeek

SYNTAX: int cBuf_LastPeek(char *circularBuffer);

DESCRIPTION: Returns the last byte of data.

PARAMETER1: circularBuffer: Circular buffer.

RETURN VALUE: -1 if the buffer is empty, 1st data character if not.
END DESCRIPTION **********************************************************/

#asm xmem

cBuf_LastPeek::
push ix ; 12, save frame pointer

ld		ix,(sp+RETADDRESS_SIZE+2)		; 11, ix=cbuf

ld		hl,(ix+2)		; 9,	hl=front
ld		c,l				; 2	start moving hl into bc, ld bc,hl
ld		b,h				; 2	bc=front

ld		hl,(ix+4)		; 9,	hl=back

or		a					; 2,	clear carry

sbc	hl,bc				; 4,	front==back???
jr		nz,.cbpk_nempty	; 5
dec	hl					; 2	buffer is empty so make hl = -1
jr		.cbpk_done		; 5

.cbpk_nempty:
ld hl,(ix+4) ; 9, hl=back
bool hl ; 2 test if HL = 0 (this kills hl, so we need to reload it)
jr nz,.reloadBack ; 5 need to check if back = 0

ld		hl,(ix+6)		; 9,	hl = mask = size of buffer
inc	hl					; since hl will be decremented later
jr		.getValue	; 5	goto where char is loaded

.reloadBack:
ld hl,(ix+4) ; 9, hl=back

.getValue:
dec hl ; 2 step back one spot since char is just before the “back” pointer
ld c,l ; 2 start moving hl into bc, ld bc,hl
ld b,h ; 2 bc=back

ld		hl,ix				; 4,	hl=&buffer
add	hl,bc				; 2	offset by value of "back"
ld		bc,0x0008		; 6	offset by buffer's 8 byte header
add	hl,bc				; 2	hl=&buffer[front]
ld		a,(hl)			; 5	load char into a
bool	hl					; 2	set HL=1, fast way to clear op byte
ld		l,a				; 2	put the char into l

.cbpk_done:
pop ix ; 9
lret ; 8 return to calling program

#endasm //cBuf_LastPeek

/*** Beginheader MySerBlastPeek /
int MySerBlastPeek();
/
** endheader */

/* START FUNCTION DESCRIPTION ********************************************
MySerBlastPeek

SYNTAX: int MySerBlastPeek();

DESCRIPTION: returns the last character of the data in the B input buffer.
This function is non-reentrant.

PARAMETER1: None

RETURN VALUE: -1 if the buffer is empty, the 1st character of the data if not
END DESCRIPTION **********************************************************/

nodebug int MySerBlastPeek()
{
return (int)cBuf_LastPeek(spb_icbuf);
} //MySerBlastPeek