usb-avr-cpld experiment board with FTDI FT232RL, ATMEGA88 & XC9572XL
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
1.5 KiB

  1. #include <avr/io.h>
  2. #include <avr/interrupt.h>
  3. #include <stdint.h>
  4. #ifndef F_CPU
  5. #warning "F_CPU wasn't set in makefile, so we do it now with 10.0 MHz"
  6. #define F_CPU 10000000UL
  7. #endif
  8. // setting baud rate
  9. #define BAUD 9600UL
  10. // uart baud rate checks
  11. #define UBRR_VAL ((F_CPU+BAUD*8)/(BAUD*16)-1)
  12. #define BAUD_REAL (F_CPU/(16*(UBRR_VAL+1)))
  13. #define BAUD_ERROR ((BAUD_REAL*1000)/BAUD)
  14. #if ((BAUD_ERROR<990) || (BAUD_ERROR>1010))
  15. #warning baudrate error higher than 1%!
  16. #endif
  17. static void uart_init (void);
  18. static void uart_putc (unsigned char c);
  19. volatile uint8_t got_char;
  20. volatile unsigned char rx_char;
  21. int main (void)
  22. {
  23. // uart rx initialisation
  24. uart_init();
  25. // activate global interrupts
  26. sei();
  27. while(1)
  28. {
  29. if(got_char) {
  30. UCSR0B &= ~(1<<RXCIE0);
  31. uart_putc(rx_char);
  32. got_char = 0;
  33. UCSR0B |= (1<<RXCIE0);
  34. }
  35. }
  36. return 0;
  37. }
  38. // function to init uart
  39. static void uart_init (void) {
  40. // set baudrate registers (high byte first!)
  41. UBRR0H = UBRR_VAL >> 8;
  42. UBRR0L = UBRR_VAL & 0xFF;
  43. // tx enable
  44. UCSR0B |= (1<<TXEN0) | (1<<RXEN0) | (1<<RXCIE0);
  45. // frame format: async mode, no parity, 1 stop bit, 8 bit size
  46. UCSR0C |= (3<<UCSZ00);
  47. }
  48. // send a byte on uart
  49. static void uart_putc (unsigned char c) {
  50. while (!(UCSR0A & (1<<UDRE0))) {}
  51. UDR0 = c;
  52. }
  53. ISR(USART_RX_vect) {
  54. uint8_t rx_error = 0;
  55. //check for frame error
  56. if (UCSR0A & (1<<FE0)) {
  57. rx_error = 1;
  58. }
  59. // save rx buffer
  60. rx_char = UDR0;
  61. // signalise the new rx char if no frame error occured
  62. if (!rx_error) {
  63. got_char = 1;
  64. }
  65. }