Skip to content

Commit dd18276

Browse files
committed
fix(gpio): pinState() value incorrect in GPIO listeners
fix #9
1 parent f1b3ea3 commit dd18276

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

src/gpio.spec.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,5 +68,19 @@ describe('GPIO', () => {
6868
cpu.writeData(0x25, 0x2); // PORTB <- 0x2
6969
expect(port.pinState(1)).toEqual(PinState.InputPullUp);
7070
});
71+
72+
it('should reflect the current port state when called inside a listener', () => {
73+
// Related issue: https://github.com/wokwi/avr8js/issues/9
74+
const cpu = new CPU(new Uint16Array(1024));
75+
const port = new AVRIOPort(cpu, portBConfig);
76+
const listener = jest.fn(() => {
77+
expect(port.pinState(0)).toBe(PinState.High);
78+
});
79+
port.addListener(listener);
80+
expect(port.pinState(0)).toBe(PinState.Input);
81+
cpu.writeData(0x24, 0x01); // DDRB <- 0x01
82+
cpu.writeData(0x25, 0x01); // PORTB <- 0x01
83+
expect(listener).toHaveBeenCalled();
84+
});
7185
});
7286
});

src/gpio.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,10 +96,11 @@ export class AVRIOPort {
9696
constructor(private cpu: CPU, private portConfig: AVRPortConfig) {
9797
cpu.writeHooks[portConfig.PORT] = (value: u8, oldValue: u8) => {
9898
const ddrMask = cpu.data[portConfig.DDR];
99+
cpu.data[portConfig.PORT] = value;
99100
value &= ddrMask;
100101
cpu.data[portConfig.PIN] = (cpu.data[portConfig.PIN] & ~ddrMask) | value;
101102
this.writeGpio(value, oldValue & ddrMask);
102-
// TODO: activate pullups if configured as an input pin
103+
return true;
103104
};
104105
cpu.writeHooks[portConfig.PIN] = (value: u8) => {
105106
// Writing to 1 PIN toggles PORT bits

0 commit comments

Comments
 (0)