Skip to content

Commit 4eaf664

Browse files
committed
fix(timer): setting TCNT doesn't update OCRA #111
1 parent d104976 commit 4eaf664

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/peripherals/timer.spec.ts

+36
Original file line numberDiff line numberDiff line change
@@ -1209,6 +1209,42 @@ describe('timer', () => {
12091209
expect(cpu.readData(R19)).toEqual(0x6);
12101210
expect(cpu.readData(R20)).toEqual(0x7);
12111211
});
1212+
1213+
it('should update OCR1A when setting TCNT to 0 (issue #111)', () => {
1214+
const { program, instructionCount } = asmProgram(`
1215+
CLR r1 ; r1 is our zero register
1216+
LDI r16, 0x0 ; OCR1AH = 0x0;
1217+
STS 0x89, r1
1218+
LDI r16, 0x8 ; OCR1AL = 0x8;
1219+
STS 0x88, r16
1220+
; Set waveform generation mode (WGM) to PWM Phase/Frequency Correct mode (9)
1221+
LDI r16, 0x01 ; TCCR1A = (1 << WGM10);
1222+
STS 0x80, r16
1223+
LDI r16, 0x11 ; TCCR1B = (1 << WGM13) | (1 << CS00);
1224+
STS 0x81, r16
1225+
STS 0x85, r1 ; TCNT1H = 0x0;
1226+
STS 0x84, r1 ; TCNT1L = 0x0;
1227+
1228+
LDI r16, 0x5 ; OCR1AL = 0x5; // TCNT1 should read 0x0
1229+
STS 0x88, r16 ; // TCNT1 should read 0x2 (going up)
1230+
STS 0x84, r1 ; TCNT1L = 0x0;
1231+
LDS r17, 0x84 ; // TCNT1 should read 0x1 (going up)
1232+
LDS r18, 0x84 ; // TCNT1 should read 0x3 (going up)
1233+
LDS r19, 0x84 ; // TCNT1 should read 0x5 (going down)
1234+
LDS r20, 0x84 ; // TCNT1 should read 0x3 (going down)
1235+
`);
1236+
1237+
const cpu = new CPU(program);
1238+
new AVRTimer(cpu, timer1Config);
1239+
1240+
const runner = new TestProgramRunner(cpu);
1241+
runner.runInstructions(instructionCount);
1242+
1243+
expect(cpu.readData(R17)).toEqual(0x1);
1244+
expect(cpu.readData(R18)).toEqual(0x3);
1245+
expect(cpu.readData(R19)).toEqual(0x5);
1246+
expect(cpu.readData(R20)).toEqual(0x3);
1247+
});
12121248
});
12131249

12141250
describe('External clock', () => {

src/peripherals/timer.ts

+8
Original file line numberDiff line numberDiff line change
@@ -576,6 +576,14 @@ export class AVRTimer {
576576
if (this.tcntUpdated) {
577577
this.tcnt = this.tcntNext;
578578
this.tcntUpdated = false;
579+
if (
580+
(this.tcnt === 0 && this.ocrUpdateMode === OCRUpdateMode.Bottom) ||
581+
(this.tcnt === this.TOP && this.ocrUpdateMode === OCRUpdateMode.Top)
582+
) {
583+
this.ocrA = this.nextOcrA;
584+
this.ocrB = this.nextOcrB;
585+
this.ocrC = this.nextOcrC;
586+
}
579587
}
580588
if (this.updateDivider) {
581589
const { CS } = this;

0 commit comments

Comments
 (0)