Hello, community!
I try to set up communications between my AVRs and PC. I followed this awesome tutorial on UART and very basic test (sending the letter 'A') "works" with the following code:
#include <avr/io.h> #include <util/delay.h> #define USART_BAUDRATE 9600 #define BAUD_PRESCALE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1) int main(void) { UCSRB = (1 << RXEN) | (1 << TXEN); // enable UART UCSRC = (1 << UCSZ1) | (1 << UCSZ0); // 8-bit data frames UBRRH = (BAUD_PRESCALE >> 8); // set baud rate UBRRL = BAUD_PRESCALE & 0xFF; while (1) { while ((UCSRA & (1 << UDRE)) == 0) {}; UDR = 'A'; } }
Serial settings: 9600 baud rate, no parity bit, 1 stop bit. I use cutecom 0.50 (running ahead: minicom, screen and other tools including my own C-programs give the same result) on Archlinux with the latest stable kernel available. But I experience the following problem: sometimes when I open serial port via my terminal I see the right letter 'A' (0x41 hex) and sometimes I see total garbage. Fast reconnects is the possible way to resync (?) and after some tries and fails I get the proper letter in terminal.
I tried a lot and there is some results observed:
HEX | BIN |
---|---|
0x05 | 00000101 |
0x15 | 00010101 |
0x2a | 00101010 |
0x41 | 01000001 |
0x50 | 01010000 |
0x54 | 01010100 |
0xa8 | 10101000 |
As soon as I send the letter 'A' via UART and use the settings listed above I expect that one frame of data should look like this: 0 01000001 1 (according to the RS-232 spec). But as you could see from the results table often some patterns of 10101 occur shifted by some zero bits and this pattern can't be the direct product of messing with the start bit of initial data frame. However, the problem could be mitigated if I add some delay (e. g. 100 ms) after the single transfer but not fixed at all. Also setting 2 stop bits for transfer protocol slightly improves results.
I use MAX232CPE+ as TTL to RS-232 level converter and the 10 uF electrolytic caps with it (schematics are included in attachment). Also I use 11.0592 MHz crystal oscillator for the chip so there should be no problem with UART errors. As for AVRs: the problem persists for both ATmega8 and ATtiny2313 chips.
I wonder why this problem arises even for so small baud rates (on 1200 it could be observed too) and can't find any successfull solution for it so any advice will be great.
Thank you