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
463 stars 73 forks source link

Serial port (USART TX) should respect the given baud rate #16

Closed urish closed 3 years ago

urish commented 4 years ago

In the current implementation, whenever a byte is sent through the Serial port (USART), we immediately acknowledge it. In practice, sending data through the AVR Serial port takes time. For instance, if we use 9600 baud rate, we can send about 960 bytes per second (each byte requires 10 bits in total: 1 start bit, 8 data bits, and 1 stop bit). Thus, we should only mark the transfer completed after ~1.04ms (or ~16667 clock cycles when running in 16MHz).

In other words, when running the following program:

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("Hello, Serial!");
}

We should get about 60 lines printed every second ("Hello, Serial!\r\n" is 16 bytes, and 960/16 == 60).

When calculating the delay before setting the TX Complete flag after each byte transmission, we ideally need to take the following parameters into account:

In practice, most implementations only change the baud rate (9600 and 115200 are probably the most common values), and the other parameters are static (8 bits per bytes, no parity, 1 stop bit), so we can decide to start only with the baud rate.

Information about the USART registers can be found in page 200 / section 20.11 of the datasheet.

LironHazan commented 4 years ago

:sparkle: on it :)

LironHazan commented 4 years ago

@urish Thanks!