All,
I'm new to 6502 programming. I bought a PAL-1 and I'm learning about 6502 programming and microprocessors. In the process, I found and read Don Lancaster's Micro Cookbooks... great books for folks like me, who never did any hardware or low level programming, btw. Anyway, one of the problems he presents (Discovery Module #4 - Audio Tone) requires the programmer to code up a 500us Low, 500us High square wave to fake an audio tone (it's not a sine wave, but it'll do). So I coded it up and ran it. Interestingly, it ran 500.25us low and 500.50us high. Here's my code and logic:
The flow was to:
Clear the decimal flag
Teach the port PB0 to be output
LOOP:
Output LO
Delay 491us
Output HI
Delay 491us
The Code:
Code:
0200 D8 CLD ; clear decimal mode
0201 A9 01 LDA #$01 ; prepare to set PB0 to output
0203 8D 03 17 STA $1703 ; set PB0
0206 A9 00 GOLO: LDA #$00 ; prepare to set PB0 LO
0208 8D 02 17 STA $1702 ; set PB0 LO
020B A2 62 LDX #$62 ; set counter to 62 hex
020D CA D1: DEX ; decrement the counter
020E D0 FD BNE D1 ; we there yet?
0210 4C 13 02 JMP GOHI ; yup, GOHI
0213 A9 01 GOHI: LDA #$01 ; prepare to set PB0 HI
0215 8D 02 17 STA $1702 ; set PB0 HI
0218 A2 62 LDX #$62 ; set counter to 62 hex
021A CA D2: DEX ; decrement the counter
021B D0 FD BNE D2 ; we there yet?
021D 4C 06 02 JMP GOLO ; yup, GOLO
0220 XX
There are 9 cycles of instructions - JMP (3), LDA (2), STA (4) between each delay loop (D1 and D2).
The desired cycle time for the square wave is 500us LO and 500us HI. So, the delay between states needs to be 500 - 9 cycles = 491us.
The delay loops use 5N - 1 cycles for the loop (5 cycles for each time through save the last, which only takes 4... DEX (2), BNE (3 for branching, 2 for not branching). Setup of the loop takes 2 cycles - LDX (2). So, each loop takes 5N+1 cycles.
Setting 5N+1 = 491 (the desired delay in us), N=98 (62H).
My question is - should I expect to get exactly 500us hi and 500us lo and if so, what kinds of things could be causing the discrepancy?