Skip to content

Ghetto Programmer Meets UV EPROM

The Cypress CY27C256T is a UV erasable EPROM.  Mostly those are the wide .6″ DIP’s  but this is available in a .3″ wide package which means it will fit under the non-volatile RAM on the membership card. That spot is meant for a RAM but the pinouts are similar enough that I should be able to make it work for at least the bottom part of the address space.  To program it I’m adapting my ghetto eeprom programmer which I last used for the Boyd Calculator reprogramming.  I don’t want to bollix it permanently so I’m trying to be careful with the changes.  The first try is a read test. For  this all I had to do was connect pin 1(VPP) to +V along with pins 27(MA14) and 26(MA13), pin 23(MA11) goes to A11. Probably if I were smarter I’d make an adapter socket to match up with the footprint for the AT28C64 that the programmer was originally made for.  For now, I’ll just have to be careful.

17-05-22 ghetto 27c256I fired it up and it does read as 0’s which is good. I was also able to measure the 5V current at 27MA(including the 74595) and, by switching the /CE to +V, put the chip in low power mode and see the current drop to 7MA.

To actually program it I have to set VPP(pin 1) to 12V with /OE and /CE held high then pulse /CE low many times for 200us at a time until the programming takes.  Then do it twice as many times again.  Fortunately the VPP is static at 12V so if i can figure out how to source it I don’t have to pulse it.  The ghetto programmer doesn’t normally control /CE but there’s no /WE required so that signal is freed up to use(the arduino’s D2).

Below is stuff I’m gathering for the programming push:

17-05-22 WS27C256 fit to programmer

17-05-22 WS27C256 fit to U2

As regards putting the EPROM chip into the Membership card, I have to think about pins 1,20, and 27. As currently routed, pin 1(VPP) will fluctuate with A14 which theoretically is ok. pin 20(/CE) needs to be wired to some variant of A15 to divide the address space with the RAM and pin 27(A14) would fluctuate with /WE which again theoretically doesn’t matter for testing since I won’t write in the ROM. So, hell, I may just be able to leave it all alone except for whatever jumpers lee provides for addressing.  Aaand it looks like the default jumpers on the board address the ROM high and the RAM low.  Perfect for my first programming attempt.  I’ll write something in the high part of the chip and then see if i can read it with the 1802.

Programming Instructions for the CY27C256

datasheet

membership card schematic

UPDATE: Poking around my pile of castoffs I have a 12V wall wart that actually delivers just a bit over 12V.  I may try to get a regulator tomorrow or i may just try it out.

Below is the EPROM in place under the RAM.  I actually have to solder in some pin sockets and a capacitor before i run it but the fit looks fine.

27-05-22 ROM under RAM

Another Stab at Xmodem

17-05-05 xmodem test rig
Xmodem is a very simple and easy to understand protocol but i have spent a LOT of time diddling with it. I’m trying to combine it with some bit bang serial routines for the 1802 as a return to a serial bootloader.  I’m really just using xmodem for pacing and i’m not checking any error conditions. Testing it involved my usual “fantastic collection of stamps” approach with a python sender on windows, a couple of serial ports, and the logic analyzer.

After hours of flaky results it finally started working today when I overwrote low memory and had to switch back from the 1806 to the 1802.  Now it seems bulletproof! I’ll retry with the 1806 tomorrow with some confidence that i can make it work.

The reason for the custom python sender is so i could build up from working with very small blocks and visible control characters. I’m munging all the code together here so i can track where i was when it started working.

#include <olduino.h>
#include <nstdlib.h>
#include <cpu1802spd4port7.h>
int XR(unsigned char *);
void dump(unsigned char* data, unsigned int len){
	unsigned int i=0;
	printf("dumping %d bytes at %x",len,data);
	for(i=0;i<len;i++){
		if (0==(i%8)) printf("\n%x ",data);
		printf("%cx ",*data++);
	}
	printf("\n");
}
void main(){
	int ret;
	asm(" seq\n"); //make sure Q is high to start
	ret=XR((unsigned char *)0x7000);
	printf("XR returns %x\n",ret);
	dump((unsigned char *)0x7000,ret-0x7000-1);
	while(1);
}
void includeser(){
	asm(" include xrwjr2.asm");
}
#include <olduino.c>
#include <nstdlib.c>
**************xrwjr2,asm include file follows ***************
NAK:	EQU 0x15;'N'
SOH:	EQU 0x01;'S'
EOT:	EQU 0x04;'T'
ACK:	EQU 0x06;'K'
Rrcv:	EQU 8
Rsnd:	EQU 9
blksize:	EQU 128
trc:	MACRO
	dec 2
	str 2
	out 7
	ENDM
; XMODEM receiver based on xr.asm by Michael H Riley and serial routines by Josh Bensadon
; See bottom of file for full acknowledgements and links.
; On entry R12 points to memory where received data will go
; On exit R15 has the last byte written
	align 64
_XR:	   ldaD	   Rsnd,serout
	   ldaD    Rrcv,serin
	ldi '<' 	trc  	   ldi     NAK                 ; need to send NAK to start            sep     Rsnd filelp:    ;receive address is in R12, length goes in R11 ;begining of block read. returns to filelp or exits to filedn   				            sep     Rrcv               ; wait for next incoming character            smi     EOT              ; check for EOT            lbz     filedn           ; jump if so 	   sep     Rrcv               ; read block number            sep     Rrcv               ; read inverted block number            ldi     blksize             ; 128 bytes to receive            plo     r11 readlp:    sep     Rrcv               ; read data byte            str     r12                  ; store into output buffer            inc     r12                  ; point to next position            dec     r11                  ; decrement block count            glo     r11                  ; see if done            bnz     readlp              ; loop back if not ;end of block read            sep     Rrcv               ; read checksum byte            ldi     ACK                  ; send an ACK            sep     Rsnd            lbr     filelp              ; loop back for more filedn:                ldi     ACK                  ; acknowledge end of transmission            sep     Rsnd 	   glo	   R12			;copy last address to return register 	   plo     R15 	   ghi     R12 	   phi     R15 	ldi '>'
	trc
           cretn	           	; and return to caller

; *******************************************************************
; *** This software is copyright 2005 by Michael H Riley          ***
; *** You have permission to use, modify, copy, and distribute    ***
; *** this software so long as this copyright notice is retained. ***
; *** This software may not be used in commercial applications    ***
; *** without express written permission from the author.         ***
; *******************************************************************
;**********************************************************************
;bit-bang Serial routines adapted from Josh Bensadon's VELFbios-v3.1.asm
;Transmit Byte via Q connected to RS232 driver
;call via SCRT
;Byte to send in D
;Destroys r14
;----------------------------------------------------------------------
 	IFNDEF 	LCC1802CPUSPEED
LCC1802CPUSPEED EQU 4000000
 	ENDIF
bitdelay: MACRO baudrate,cpuspeed,baseline,xreg
	rept ((cpuspeed/(baudrate*8)-baseline))/3
	NOP
	endm
	rept (((cpuspeed/(baudrate*8)-baseline)#3))>=1
	sex xreg
	endm
	ENDM
__BAUDRATE EQU 	9600
	align 32
serout:			;entry from assembly with char in D
	phi R14		;save char in R14.1
	ldi 9		;9 bits to transmit (1 start + 8 data)
	plo r14
	ghi R14
	shl		;set start bit
	rshr		;DF=0

.txcloop:
	bdf $+5		;10.5   jump to seq to send a 1 bit
	req		;11.5   send a 0 bit
	br $+5		;1      jump +5 to next shift
	seq		;11.5   send a 1 bit
	br $+2		;1      jump +2 to next shift (NOP for timing)
	rshr		;2      shift next bit to DF flag
	phi r14		;3      save D in r14.1
	DEC r14		;4      dec bit count
	glo r14		;5      get bit count
	bz .txcret	;6      if 0 then all 9 bits (start and data) sent
	ghi r14		;7      restore D
	bitdelay __BAUDRATE,LCC1802CPUSPEED,20,2
	br .txcloop	;9.5    loop back to send next bit
.txcret: ghi r14		;7
	bitdelay __BAUDRATE,LCC1802CPUSPEED,16,2
	seq		;11.5 stop bit
	bitdelay __BAUDRATE,LCC1802CPUSPEED,4,2
	sep R3		;return
	br serout	;reset for next time
;**********************************************************************
;rx_char
;Receive Byte via EF2 connected to RS232 receiver
;Receives 8 bits
;call via sep
;Returns with Byte received in D
;Destroys r14.0
;----------------------------------------------------------------------
	align 32
serin:
 	ldi 8		;start bit +7 bits from loop, last bit on returning
	plo r14
	ldi 0
.rxcw:			;wait for start bit
	bn3 .rxcw	;each instr takes 9us, we need 104us = 11.5
			;delay 1/2 bit time to center samples
	NOP		;     Don't test for correct start bit
	NOP		;     it will work. if there's too much
	NOP		;     noise on the line, shorten the cable!
.rxcloop:
	bitdelay __BAUDRATE,LCC1802CPUSPEED,20,2
	b3 $+6		;11.5 sample rx input bit
	ori 80h		;1
	br $+4		;2
	phi r14		;1
	phi r14		;2
	shr		;3
	phi r14		;4
	DEC r14		;5
	glo r14		;6
	bz .rxcret	;7
	ghi r14		;8
	br  .rxcloop	;9
.rxcret: ghi r14	;8
	ghi r14		;9
	bitdelay __BAUDRATE,LCC1802CPUSPEED,20,2
	b3 $+4		;11.5 sample last rx input bit
	ori 80h		; for a 1 bit
	sep R3		;return
	br  serin	;for next time

_putcser:
	ldad Rsnd,serout
	glo R12
	sep Rsnd
	cretn

_getcser:
	ldad Rrcv,serin
	sep Rrcv
	plo R15
	ldi 0
	phi R15
	cretn

************************SSX3.PY custom sender follows *****************
from __future__ import print_function
import sys
import logging
logging.basicConfig()
import serial
try:
    from cStringIO import StringIO
except:
    from StringIO import StringIO
from time import sleep
import os
if len(sys.argv)>1:
    filename=sys.argv[1]
else:
    filename="xserial.c"
fileSize=os.path.getsize(filename)
print ("File Size is",fileSize)

def xmodem_send(serial, file):
	NAK='\x15'
	blocksize=128
	t=0
	#	t, anim ='|/-\\'
	while 1:
	    if serial.read(1) != NAK:
		t = t + 1
		print ('.')
		if t == 3 : return False
	    else:
		break

	p = 1
	s = file.read(blocksize)
	while s:
	    s = s + '\xFF'*(blocksize - len(s))
	    chk = 0
	    for c in s:
		chk+=ord(c)
		#print (c,ord(c),chk,chk%256)
	    while 1:
		serial.write('\x01')#('S') #SOH)
		print('S')
		serial.write(chr(p))
		print('n')
		serial.write(chr(255 - p))
		print('-')
		serial.write(s)
		print(s)
		serial.write(chr(chk%256))
		#serial.write('ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ')
		print('c')
		serial.flush()
		print ('checksum is ',format(chk%256, '02X'),end=' ')
		answer = serial.read(1)
		if len(answer)!=0:
			print('answer is ',format(ord(answer[0]), '02X'))
		else:
			print ("Timeout I guess")
		if  answer == '\x15': continue
		if  answer == '\x06': break
		return False
	    s = file.read(blocksize)
	    p = (p + 1)%256
	    print ('.')
	serial.write('\x04')#('T')
	serial.flush()
	sleep(.1)
	serial.write('TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT')
	serial.flush()

	return True

#Main program starts here - define the serial port, set RTS off, then open it
#open the file to be loaded
stream = open(filename,'rb')

port = serial.Serial(parity=serial.PARITY_NONE,
                     bytesize=serial.EIGHTBITS,
                     stopbits=serial.STOPBITS_ONE,timeout=10,xonxoff=0,
                     rtscts=0,dsrdtr=0,baudrate=9600)
port.rts=False
port.port='COM4'
port.open()
port.rts=True
sleep(0.001)
port.rts=False
port.flushInput()
#transfer the file
result=xmodem_send(port, stream)

stream.close()
port.close()

if result:
    print ("\ntransfer successful")
    sleep(.25)
else:
    print ("\ntransfer unsuccessful")
    #x=raw_input("press enter to continue...");

I always want the last word so that wordpress doesn’t eat my code!

Reprogramming an 1805-Based Calculator in C



A few weeks ago one of the fellows on the Cosmac Elf mailing list spotted some surplus calculators based on the CDP1805 processor chip.  This is a follow-on to the 1802 with a few extra instructions and a 64 byte onboard ram.  Much discussion ensued and many of us bought the calculators for novelty value or to hack.  I, of course, set out to re-program mine in C with the idea of implementing a “little language” that would output some sort of ascii art or patterns on the printer.

The baseline calculator dates from the eighties and was made as a contractors tool for doing math with feet, inches, and sixteenths.

It’s very well made: all through-hole parts with no fewer than three processors.  The 1805 does the actual calculations and there’s a seiko and an 80c49 that are dedicated to the printer.  Opening it up we see a main PCB that has the 1805 logic and a 4K 2532 eprom. On top of that is a daughter board with the printer and display.  The display uses a 7218B display driver that can be jumpered to display decimal digits plus a few characters of to display hex 0-F.  Everything is nicely done with good quality connectors and screws for assembly.

Josh Bensadon on the mailing list went at the 1805 code with a will and produced a beautifully commented disassembly showing how the display, keyboard, and printer worked.  The code is not concise but it’s pretty easy to follow (thanks Josh!).

I’ve replaced the 4K EPROM with a 2K flash EEPROM which is faster and easier for me to program. I re-jumpered the display chip to display hex instead of decimal.  This gives up the ability to display blanks but it seemed worth it for hacking.  To program it, I’m working in C to produce a hex file.  That gets converted to a C header file for an arduino program that writes the EEPROM which I then move over into the calculator.  It’s a bit outlandish but it works.

The code is standard LCC1802 but I have jiggered the epilog code to leave out the math routines.  That keeps things pretty easily within the 2K EEPROM space. At first, when i was just displaying memory, working in C seemed painful but when i started implementing my “little language” it felt much better.  So far the “language” is all two byte instructions:

  • 00 xx is display the memory at location 10xx (that’s where the 64 byte ram is located)
  • 01 xx is increment the memory location
  • 02 xx is goto
  • 03 nn is delay nn*4 ms
  • 04 xx is display the bottom byte of the stack pointer(xx is ignored)

The monitor just implements the basic functions:

  • display memory, moving backward and forward with + and – keys
  • switch between the eeprom memory at 0 and the 64 byte onboard RAM at 0x1000 with the REM key
  • Change memory by pressing MS and two hex keys
  • Begin interpreting the program at the location counter by pressing the X key (times)

The 04xx instruction displays 20 meaning that the stack has used up 32 of 64 bytes leaving 32 for the “little language” program.  I haven’t tried but i would think I could improve that.  For example main() gets entered by subroutine call and saves 4 registers but it’s never going to return or restore them. Execute() similarly saves 4 registers so if i had to move that inline in main()I’d have 16 bytes free right there.

Looking at the compiled program It uses the EEPROM up to 0x5B6 leaving another 500-600 bytes for “little language” features. After all – I have a total of 2,112 bytes of memory.  Surely that ought to be enough for anybody!

Here’s the working version of the monitor/interpreter and one assembly include where I adapted some of josh’s disassembly of the original code. The keyboard is conceptually a matrix of 7X4 keys. A row of keys is activated by doing an OUT to port 1,2,3,4,5 or 6 or by setting Q and pressing a single key will assert one of EF1 to 4.

 #include "olduino.h"
#define initleds() 	asm(" req\n seq\n dec 2\n out 7\n req\n")
unsigned char boydscan();
void boydinc(){
	asm(" include \"boydscan.inc\"\n");
}
void disp1(unsigned char d){//display a byte as two hex digits
	asm(" glo 12\n ani 0x0f\n" //prep bottom digit
		" dec 2\n str 2\n out 7\n"
		" glo 12\n shr\n shr\n shr\n shr\n" //prep top digit
		" dec 2\n str 2\n out 7\n"
		);

}

void dispmemloc(unsigned char * loc){
	register unsigned int lint;
	initleds();
	disp1(*(loc+1));
	disp1(*loc);
	lint=(unsigned int)loc;
	disp1((unsigned int)loc&0xff);
	disp1(lint>>8);
}
void dispval(unsigned char v){
	register unsigned int i;
	initleds();
	disp1(v);
	for (i=6;i!=0;i--) out(7,0);

}
unsigned int getsp(){//return stack pointer value
	asm(" cpy2 r15,sp\n"  	//copy stack pointer to return reg
		" cretn\n");		//return it to the caller;
	return 0;				//not executed
}
unsigned char * execute(unsigned char * loc){
	unsigned char op,val;
	unsigned char * mp;
	while(1){
		op=*loc; val=*(loc+1);
		switch (op){
			case 0: //display memory at mem[val];
				mp=(unsigned char *)(4096+val);
				dispval(*mp); delay(1000);
				break;
			case 1: //increment location val
				mp=(unsigned char *)(4096+val);
				*mp+=1;
				break;
			case 2: //goto val
				loc=(unsigned char *)(val+4096-2); //ugh
				break;
			case 3: //delay val*4 ms
				delay(val*4);
				break;
			case 4: //display stack pointer;
				dispval(getsp());
				delay(250);
				break;
			default:
				dispval(0x41); delay(250);
				dispmemloc(loc); delay(5000);
				break;
		}
		loc+=2;
	}
	return loc;
}

void main()
{
	unsigned char * loc=0;
	unsigned char memtype='o'; //displaying o=eeprom,a=ram
	unsigned char k,k2;
	dispval(0x42);
	delay(1000);
	while(1){
		dispmemloc(loc);
		k=boydscan();
		switch(k){
			case 16: //+
				loc +=1;
				break;
			case 17: //-
				loc -=1;
				break;
			case 18:	//rem
				if (memtype=='o'){
					loc=(unsigned char *)4096;
					memtype='a';
				}else{
					loc=(unsigned char *)0;
					memtype='o';
				}
				break;
			case 19: //ms
				dispmemloc(loc); //makes a blink
				k=boydscan(); dispval(k); delay(250);
				k2=boydscan(); dispval(k2); delay(250);
				*loc=(k<<4)+k2;
				break;
			case 20: //X for execute
				dispval(0x45);
				delay(250);
				loc=execute(loc);
				break;
			default:
				dispval(k);
				delay(250);
		}
	}
}

#include "olduino.c" //for the delay routine
_boydscan:			;SCAN THE KEYBOARD
		sex	r14 	;set up "don't care" X register
		rldi	r15,0	; r15 is return value
.scan:		OUT	1                     ;109: 61
		B1	.KEY_12                     ;10A: 34 50
		B2	.KEY_8                      ;10C: 35 60
		B3	.KEY_4                      ;10E: 36 70
		B4	.KEY_0                      ;110: 37 80
		OUT	2                     ;112: 62
		B1	.KEY_13                     ;113: 34 54
		B2	.KEY_9                      ;115: 35 64
		B3	.KEY_5                      ;117: 36 74
		B4	.KEY_1                      ;119: 37 84
		OUT	3                     ;11B: 63
		B1	.KEY_14                     ;11C: 34 58
		B2	.KEY_10                     ;11E: 35 68
		B3	.KEY_6                      ;120: 36 78
		B4	.KEY_2                      ;122: 37 88
		OUT	4                     ;124: 64
		B1	.KEY_15                     ;125: 34 5C
		B2	.KEY_11                     ;127: 35 6C
		B3	.KEY_7                      ;129: 36 7C
		B4	.KEY_3                      ;12B: 37 8C
		OUT	5                     ;12D: 65
		B1	.KEY_DIV_WHOLE              ;12E: 34 99
		B2	.KEY_MUL                    ;130: 35 96
		B3	.KEY_SUB                    ;132: 36 93
		B4	.KEY_ADD                    ;134: 37 90
		OUT	6                     ;136: 66
		B1	.KEY_REM                    ;137: 34 A5
		B2	.KEY_MEM_STORE              ;139: 35 A2
		B3	.KEY_MEM_RECALL             ;13B: 36 9F
		B4	.KEY_EQU                    ;13D: 37 9C
		SEQ                                ;13F: 7B
		B1	.KEY_DIV_FIS                ;140: 34 B1
		B2	.KEY_CLEAR                  ;142: 35 AE
		B3	.KEY_CLR_ENTRY              ;144: 36 AB
		B4	.KEY_INV_SIGN               ;146: 37 A8
		REQ                                ;148: 7A
;here we have no keys pressed, if r15.0 has a value, return it -1
		glo	r15
		bz	.scan
		dec	r15
		sex	r2	;restore the X register before returning
		cretn

.KEY_12		LDI	13                         ;150: F8  C
		BR	.KEY_SAVE                   ;152: 30 B4
.KEY_13		LDI	14                         ;154: F8  D
		BR	.KEY_SAVE                   ;156: 30 B4
.KEY_14		LDI	15                         ;158: F8  E
		BR	.KEY_SAVE                   ;15A: 30 B4
.KEY_15		LDI	16                         ;15C: F8  F
		BR	.KEY_SAVE                   ;15E: 30 B4
.KEY_8		LDI	 9                         ;160: F8  8
		BR	.KEY_SAVE                   ;162: 30 B4
.KEY_9		LDI	 10                         ;164: F8  9
		BR	.KEY_SAVE                   ;166: 30 B4
.KEY_10		LDI	11                         ;168: F8  A
		BR	.KEY_SAVE                   ;16A: 30 B4
.KEY_11		LDI	12                         ;16C: F8  B
		BR	.KEY_SAVE                   ;16E: 30 B4
.KEY_4		LDI	 5                         ;170: F8  4
		BR	.KEY_SAVE                   ;172: 30 B4
.KEY_5		LDI	 6                         ;174: F8  5
		BR	.KEY_SAVE                   ;176: 30 B4
.KEY_6		LDI	 7                         ;178: F8  6
		BR	.KEY_SAVE                   ;17A: 30 B4
.KEY_7		LDI	 8                         ;17C: F8  7
		BR	.KEY_SAVE                   ;17E: 30 B4
.KEY_0		LDI	 1                         ;180: F8  0
		BR	.KEY_SAVE                   ;182: 30 B4
.KEY_1		LDI	 2                         ;184: F8  1
		BR	.KEY_SAVE                   ;186: 30 B4
.KEY_2		LDI	 3                         ;188: F8  2
		BR	.KEY_SAVE                   ;18A: 30 B4
.KEY_3		LDI	 4                         ;18C: F8  3
		BR	.KEY_SAVE                   ;18E: 30 B4 	

.KEY_ADD	ldi	16+1
		br	.key_save
.KEY_SUB:	ldi	17+1
		br	.key_save
.KEY_MUL:	ldi	20+1
		br	.key_save
.KEY_MEM_STORE:	ldi	19+1
		br	.key_save

.KEY_REM:	ldi	18+1
		br	.key_save
.KEY_CLEAR:	req
		ldi	20+1
		br	.key_save
.KEY_INV_SIGN:	req
.KEY_CLR_ENTRY:	req
.KEY_DIV_FIS:	req
.KEY_EQU:
.KEY_DIV_WHOLE:
.KEY_MEM_RECALL:
.KEY_SAVE:	plo 15
		br .scan

Below is a video of the hoops I’ve been jumping through to load code into the calculator

And here’s the calculator baseline function:

More Advanced Inline Assembly – Nope!

LCC1802 has a simple form of inline assembly: if you code asm(“foo”); you get “foo” directly emitted in the assembly output from the compiler. This is fine for the simplest cases (seq,req etc.) but it would be nice to be able to access local variables. I found a more advanced version of the assembly patch i used which seems to be meant to do exactly that. http://www.yqcomputer.com/234_714_1.htm
This is from more than a decade ago but LCC itself is much older than that so that’s ok. I worked it into my working copy but the results so far are not encouraging:
The fragment below shows the C code and the resulting assembly code. The asm calls are just to get the substitutions for the variable names for a global:g, two parameters: p1 and p2, and two locals: L1,L2. The global g generates _g which is fine but i knew that! the locals L1 and L2 generate -4 and -6 instead of something like 2 and 0 or register references. The parameters generate 0 and 2 instead of (I would have hoped) referring to the registers or, worst case, offsets of 6 and 8 from the stack pointer. I may poke at this again and it may just be a matter of adding the frame size(which is actually 6) but in the end i question whether it’s worth it.

int g=7;
void turnqoff(int p1,int p2){
	int L1,L2;
	L1=42; L2=43;
	asm(";	L1:$L1)\n");
	asm(";	L2:$L2\n");
	asm(";	g:$g\n");
	asm(";	p1:$p1 p2:$p2\n");
}
*************compiled code follows**************
_g:
	dw 7
_turnqoff:		;framesize=6
	reserve 4
	st2 R12,'O',sp,(6+1)			
	inc memaddr	
	str2 R13,memaddr			
;void turnqoff(int p1,int p2){
;	L1=42; L2=43;
	st2I 42,'O',sp,(2+1); ASGNI2(addr,acon)
	st2I 43,'O',sp,(0+1); ASGNI2(addr,acon)
;	asm(";	L1:$L1)\n");
;	L1:-4)
;	asm(";	L2:$L2\n");
;	L2:-6
;	asm(";	g:$g\n");
;	g:_g
;	asm(";	p1:$p1 p2:$p2\n");
;	p1:0 p2:2

Making Music With the 1806 Timer Q Toggle

The 1804/5/6 have a built-in 8 bit timer/counter with a bunch of functions. In timer mode, it decrements automatically every 32 machine cycles. When it gets to 0 it resets to whatever you first set it to and counts down again. It can cause an interrupt at 0 OR, it can just toggle Q. This generates a constant square wave without any further program interference. The range, on my 4MHZ olduino is about 30HZ to 7.8KHZ. If you can set the chip up with a ROM or some other way of feeding it instructions it’s an easy way to make sure you have a genuine 1804/5/6. The 10 byte program below generates a 30HZ square wave on my 4MHZ 1806.

68 0D CID ; disable timer interrupts
F8 FF LDI 255; maximum value
68 06 LDC ;load the timer
68 09 ETQ ; enable the Q toggle
68 07 STM ; start the timer

For extra points, it occurred to me that you could use this to make music in the traditional square wave sense. I wrote a tone(frequency,duration) function that calculates the initial timer value needed and starts the timer toggling Q for the required duration. This is similar enough to the equivalent Arduino function that I was able to crib some code from github to play a simple tune. That’s what you see running in the video above. That page also has a worthwhile explanation for converting sheet music to frequency,duration pairs.

void tone(int freq, int dur){ //tone at a particular frequency for a period
	unsigned char t;
	if (0!=freq){//0 would mean quiet for the duration
		asm(" STPC ; stop the timer\n");
		if (freq>7800) t=1; calculate the number of 64us ticks
		else if (freq<30) t=255;
		else t=7800/freq;
		LDC(t);
		asm(" ETQ;  enable the Q toggle\n");
		asm(" STM; start the timer\n");
		delay(dur);
		asm(" STPC\n");
	}else{
		delay(dur);
	}
}
#define playSpeed 2
#define numNotes 29
int line1[] = {
  NOTE_D4, 0, NOTE_F4, NOTE_D4, 0, NOTE_D4, NOTE_G4, NOTE_D4, NOTE_C4,
  NOTE_D4, 0, NOTE_A4, NOTE_D4, 0, NOTE_D4, NOTE_AS4, NOTE_A4, NOTE_F4,
  NOTE_D4, NOTE_A4, NOTE_D5, NOTE_D4, NOTE_C4, 0, NOTE_C4, NOTE_A3, NOTE_E4, NOTE_D4,
  0};

int line1_durations[] = {
  8, 8, 6, 16, 16, 16, 8, 8, 8,
  8, 8, 6, 16, 16, 16, 8, 8, 8,
  8, 8, 8, 16, 16, 16, 16, 8, 8, 2,
  2};

void main(){
	unsigned int thisNote=0,noteDuration,pauseBetweenNotes;
	printf("Hello Axel Fans\n");
	asm(" CID; disable timer interrupts\n");
	for(thisNote=0;thisNote<numNotes;thisNote++){
		noteDuration = 1000/line1_durations[thisNote];
		tone(line1[thisNote], noteDuration * playSpeed);
	}
	printf("\ndone\n");

}

 

Millis Accuracy and Interrupt Overhead On the 1806

I’m working on an Arduino-style millis() function for the 1806. The idea is that I set a timer to interrupt every ms and increment a variable in memory that i can query from my code. A complication is that at 4mhz the timer counts down once every 64us which doesn’t divide evenly into 1000 – the closest you get is 16 counts for 1.024ms. So I set the counter to 16 and let it interrupt the cpu every time it counts down to 0. I increment the millis location in storage and also add 3 to a fraction variable. If the fraction goes over 125 i clear it and boost millis by one. The arduino uses exactly the same factors which is the only reason i figured it out!

unsigned int millis=0; unsigned char fractmillis=0;
void LDC(unsigned char c){
	asm(" glo r12 ; pick up the value\n"
		" LDC ;		set the timer\n");
}
unsigned char GEC(){
	asm(" GEC ;		get the value\n"
		" plo r15\n ldi 0\n phi r15 \n"
		" cretn ;	this is the actual return\n");
	return 42;//just to keep the compiler happy
}
void initmillis(){
	asm(" CID; disable timer interrupts\n");
	LDC(16);//load the timer
	asm(" ldaD R1,.handler\n");
	asm(" STM; start the timer\n");
	asm(" CIE; enable timer interrupts\n");
	return;
	asm(".done: ;millis interrupt cleanup\n"
		" INC 2	  ; X=2!\n"
		" RLXA r15\n"
		" RLXA r14\n"
		" LDA 2	  ; RESTORE DF\n"
		" SHR\n"
		" LDA 2	  ; NOW D\n"
		" RET	  ; now X&P\n");

	asm(".handler: ;actual interrupt handler prolog\n"
		" DEC 2	  ; prepare stack to\n"
		" SAV	  ; SAVE X AND P (from T)\n"
		" BCI .go ; clear timer int\n"
		".go: \n"
		" DEC 2\n"
		" STXD	  ; SAVE D\n"
		" SHLC	  \n"
		" STXD	  ; SAVE DF\n"
		" RSXD r14  ;save memaddr helper reg\n"
		" RSXD r15  ;save work reg\n");

	asm(" ld2 r15,'D',(_millis),0 ;load current millis value\n"
		" inc r15	;increase millis\n"
		" inc r14	;point to fractional part of millis\n"
		" ldn r14	;pick up fractional value immediately following\n"
		" adi 3\n str r14 ;add 3 to the fractional part and put it back\n"
		" smi 125	;test for extra count\n"
		" lbnf 		.noxtra ;no borrow, no extra counts\n"
		" str r14	;store the fraction\n"
		" inc r15	;add extra count to millis\n"
		".noxtra: 	;bypass extra count\n"
		" dec r14\n glo r15\n str r14\n"
		" dec r14\n ghi r15\n str r14\n"
		" lbr .done\n");
}
//timer test 1 - 1806 timer counter demo
#include <olduino.h>
#include <nstdlib.h>
#include <cpu1802spd4port7.h>
#include "timer1806.h"
void main()
{
	unsigned int t1,t2;
	int i,d=100;
	printf("Hello Timer Fans\n");
	asm(" seq\n");
	delay(d);
	asm(" req\n");
	initmillis();
	printf("Now we're clocking!\n");
	t1=millis;
	asm(" seq\n");
	delay(d);
	asm(" req\n");
	t2=millis;
	printf("t1=%d, t2=%d\n\n",t1,t2);
	printf("spin delay of %d ms\n",d);
	printf("covered %d timer ms\n",t2-t1);
	printf("done\n");
}
#include <nstdlib.c>
#include <olduino.c>

17-03-17 timer117-03-17 timer2
So, the bad news is in that first image where it compares the results of my millis calculation with the spin delay showing a spin delay of 100ms compared to 137ms calculated with millis. The better news is the second image which shoes two things: The actual time is almost bang on the 137ms reported by millis and the spin delay’s 100ms is actuslly 113 ms.  Still, that’s an overhead of more than 20% for tracking millis.  I can improve that in a few ways:
I Can reduce the resolution to say 10ms; I can reduce the accuracy and accept that a millisecond will be 1.024ms; I can keep the millis value in a register rather than a global memory variable. I think I’ll try reducing the resolution to 2ms and giving up the fractional ms accuracy.

Also: Ahah! I took out the timer stuff and recompiled for the 1802, then re-measured the spin delay with the logic analyzer. A 100ms nominal spin delay took 103ms with the 1802 instruction set. I think the difference is down to reserving registers 0 and 1 making them unavailable for variables.

Yup: Due to an error in the machine description file, reserving regs 0 and 1 left the compiler with only reg 7 for variable and it was going nuts spilling and reloading. I fixed the error(adding regs 4 and 5 to the pool at the same time) and the spin delay went down to almost the nominal value. Interestingly(to me) I had realized a while ago that R6 was always available for variables even though it’s the link register. Both the SCRT and SCAL/SRET always save it before using it.

So, in the end, I may leave things as they are. I bought 20% in performance with the 1806 and if i give that up for better timing, so be it.

First 1806 Counter/Timer Tests

17-03-16 ttest1

So, my first crack at the 1806 timer functions worked fine.  I set the 8 bit counter to a starting value with LDC then put it into timer mode with STM and it counts down one every 32 machine cycles(TPA’s). I get the value with two GEC’s separated by the normal olduino spin delay which just counts instructions and the results are pretty comparable. At 4MHZ the downcount happens every 64US and the range of the counter is a bit more than 16ms. That sounds too short to be useful but I’m actually planning to run it so it interrupts about every millisecond and use an interrupt routine to track milliseconds in a long int and use that for delay() and millis() ala arduino. The code below is all done in C with inline assembler because I’m lazy. the loading and getting of the timer are in functions because that’s the easiest way to get values in and out of assembly routines.

 

//timer test 1 - 1806 timer counter demo
#include <olduino.h>
#include <nstdlib.h>
#include <cpu1802spd4port7.h>
void LDC(unsigned char c){
	asm(" glo r12 ; pick up the value\n"
		" LDC ;		set the timer\n");
}
unsigned char GEC(){
	asm(" GEC ;		get the value\n"
		" plo r15\n ldi 0\n phi r15 \n"
		" cretn ;	this is the actual return\n");
	return 42;//just to keep the compiler happy
}
void main()
{
	unsigned char t1,t2;
	int i,d=16;
	printf("Hello Timer Fans\n");
	asm(" CID; disable timer interrupts\n");
	LDC(255);//load the timer
	asm(" STM; start the timer\n");
	t1=GEC();
	delay(16);
	t2=GEC();
	printf("t1=%d, t2=%d\n\n",t1,t2);
	printf("spin delay of %d ms\n",d);
	printf("covered about %f timer ms\n",(float)(t1-t2)/(15.625));
	printf("done\n");
}
#include <nstdlib.c>
#include <olduino.c>