Skip to content

Commit db422fa

Browse files
committed
fix(gpio): port state not updated on DDR write
Calling `pinState()` inside a GPIO port listener returns incorrect values after changing DDR close #47
1 parent 7da3560 commit db422fa

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

src/peripherals/gpio.spec.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,19 @@ describe('GPIO', () => {
9292
cpu.writeData(0x25, 0x01); // PORTB <- 0x01
9393
expect(listener).toHaveBeenCalled();
9494
});
95+
96+
it('should reflect the current port state when called inside a listener after DDR change', () => {
97+
// Related issue: https://github.com/wokwi/avr8js/issues/47
98+
const cpu = new CPU(new Uint16Array(1024));
99+
const port = new AVRIOPort(cpu, portBConfig);
100+
const listener = jest.fn(() => {
101+
expect(port.pinState(0)).toBe(PinState.Low);
102+
});
103+
expect(port.pinState(0)).toBe(PinState.Input);
104+
port.addListener(listener);
105+
cpu.writeData(0x24, 0x01); // DDRB <- 0x01
106+
expect(listener).toHaveBeenCalled();
107+
});
95108
});
96109

97110
describe('setPin', () => {

src/peripherals/gpio.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,8 +110,10 @@ export class AVRIOPort {
110110
constructor(private cpu: CPU, private portConfig: AVRPortConfig) {
111111
cpu.writeHooks[portConfig.DDR] = (value: u8) => {
112112
const portValue = cpu.data[portConfig.PORT];
113+
cpu.data[portConfig.DDR] = value;
113114
this.updatePinRegister(portValue, value);
114115
this.writeGpio(portValue, value);
116+
return true;
115117
};
116118
cpu.writeHooks[portConfig.PORT] = (value: u8) => {
117119
const ddrMask = cpu.data[portConfig.DDR];

0 commit comments

Comments
 (0)