wokwi / avr8js

Arduino (8-bit AVR) simulator, written in JavaScript and runs in the browser / Node.js
https://blog.wokwi.com/avr8js-simulate-arduino-in-javascript/
MIT License
461 stars 73 forks source link

Characters form serial input chunk gets discarded #127

Closed pfichtner closed 1 year ago

pfichtner commented 1 year ago

Using a node app I'm sending the node's stdin to avr8js' usart using the following code

const usart = new avr8js.AVRUSART(cpu, avr8js.usart0Config, 16e6);
process.stdin.on('data', data => {
        const bytes = data.toString();
        for (let i = 0; i < bytes.length; i++) usart.writeByte(bytes.charAt(i));
});

When typing some characters everything seems fine but when pasting clipboard text like "abc" everything but the first character "a" is lost. No matter if it's 2 or 20 characters while one char works as expected.

Same applies (without surprise) to:

const usart = new avr8js.AVRUSART(cpu, avr8js.usart0Config, 16e6);
process.stdin.on('data', data => {
        // any dummy data
        usart.writeByte(1);
        usart.writeByte(2);
        usart.writeByte(3);
});
urish commented 1 year ago

Hello @pfichtner, what project are you working on?

In general, you should feed the characters one at a time. Use the usart.onRxComplete callback to know when to transmit the next character.

You can also look at usart.rxBusy to know if the USART interface is currently busy transmitting another char. When rxBusy is false, you can call writeByte() with the next byte. When it's true, just queue the next byte (e.g. store it in an array), and have the onRxComplete callback pull the byte from the queue and call writeByte() again.

pfichtner commented 1 year ago

Thanks @urish, that worked! I start creating a project that provides a virtual avr including a virtual serial device so that I can test our generic firmware which is something similar to firmata (now I can write automated tests for the firmware) and other the other hand I can test my client program that interacts with such a device without having the need for real hardware.