Skip to content

Commit 0f2a3b0

Browse files
committed
fix(timer): OCRH masking #117
1 parent b6e5270 commit 0f2a3b0

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

src/peripherals/timer.spec.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1245,6 +1245,17 @@ describe('timer', () => {
12451245
expect(cpu.readData(R19)).toEqual(0x5);
12461246
expect(cpu.readData(R20)).toEqual(0x3);
12471247
});
1248+
1249+
it('should mask the unused bits of OCR1A when using fixed top values', () => {
1250+
const cpu = new CPU(new Uint16Array(0x1000));
1251+
new AVRTimer(cpu, timer1Config);
1252+
cpu.writeData(TCCR1A, WGM10 | WGM11); // WGM: FastPWM, top 0x3ff
1253+
cpu.writeData(TCCR1B, WGM12);
1254+
cpu.writeData(OCR1AH, 0xff);
1255+
cpu.writeData(OCR1A, 0xff);
1256+
expect(cpu.readData(OCR1A)).toEqual(0xff);
1257+
expect(cpu.readData(OCR1AH)).toEqual(0x03);
1258+
});
12481259
});
12491260

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

src/peripherals/timer.ts

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -388,11 +388,16 @@ export class AVRTimer {
388388
const updateTempRegister = (value: u8) => {
389389
this.highByteTemp = value;
390390
};
391+
const updateOCRHighRegister = (value: u8, old: u8, addr: u16) => {
392+
this.highByteTemp = value & (this.ocrMask >> 8);
393+
cpu.data[addr] = this.highByteTemp;
394+
return true;
395+
};
391396
this.cpu.writeHooks[config.TCNT + 1] = updateTempRegister;
392-
this.cpu.writeHooks[config.OCRA + 1] = updateTempRegister;
393-
this.cpu.writeHooks[config.OCRB + 1] = updateTempRegister;
397+
this.cpu.writeHooks[config.OCRA + 1] = updateOCRHighRegister;
398+
this.cpu.writeHooks[config.OCRB + 1] = updateOCRHighRegister;
394399
if (this.hasOCRC) {
395-
this.cpu.writeHooks[config.OCRC + 1] = updateTempRegister;
400+
this.cpu.writeHooks[config.OCRC + 1] = updateOCRHighRegister;
396401
}
397402
this.cpu.writeHooks[config.ICR + 1] = updateTempRegister;
398403
}
@@ -481,6 +486,16 @@ export class AVRTimer {
481486
}
482487
}
483488

489+
get ocrMask() {
490+
switch (this.topValue) {
491+
case TopOCRA:
492+
case TopICR:
493+
return 0xffff;
494+
default:
495+
return this.topValue;
496+
}
497+
}
498+
484499
private updateWGMConfig() {
485500
const { config, WGM } = this;
486501
const wgmModes = config.bits === 16 ? wgmModes16Bit : wgmModes8Bit;

0 commit comments

Comments
 (0)