uart.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. #include <avr/io.h>
  2. #include <avr/signal.h>
  3. #include <avr/interrupt.h>
  4. #include <uart.h>
  5. #define BAUDRATE 9600
  6. #define F_CPU 8000000
  7. #define nop() __asm volatile ("nop")
  8. #define SUART_TXD_PORT PORTB
  9. #define SUART_TXD_DDR DDRB
  10. #define SUART_TXD_BIT PB6
  11. static volatile uint16_t outframe;
  12. void uart_init()
  13. {
  14. uint8_t sreg = SREG, tifr = 0;
  15. cli();
  16. // Mode #4 für Timer1
  17. // und volle MCU clock
  18. // IC Noise Cancel
  19. // IC on Falling Edge
  20. TCCR1A = 0;
  21. TCCR1B = (1 << WGM12) | (1 << CS10) | (0 << ICES1) | (1 << ICNC1);
  22. // PoutputCompare für gewünschte Timer1 Frequenz
  23. OCR1A = (uint16_t) ((uint32_t) F_CPU/BAUDRATE);
  24. tifr |= (1 << OCF1A);
  25. SUART_TXD_PORT |= (1 << SUART_TXD_BIT);
  26. SUART_TXD_DDR |= (1 << SUART_TXD_BIT);
  27. outframe = 0;
  28. TIFR = tifr;
  29. SREG = sreg;
  30. }
  31. //#### TXD PART ##############################################
  32. void uart_putc (const char c)
  33. {
  34. do
  35. {
  36. sei(); nop(); cli(); // yield();
  37. } while (outframe);
  38. // frame = *.P.7.6.5.4.3.2.1.0.S S=Start(0), P=Stop(1), *=Endemarke(1)
  39. outframe = (3 << 9) | (((uint8_t) c) << 1);
  40. TIMSK |= (1 << OCIE1A);
  41. TIFR = (1 << OCF1A);
  42. sei();
  43. }
  44. SIGNAL (SIG_OUTPUT_COMPARE1A)
  45. {
  46. uint16_t data = outframe;
  47. if (data & 1) SUART_TXD_PORT |= (1 << SUART_TXD_BIT);
  48. else SUART_TXD_PORT &= ~(1 << SUART_TXD_BIT);
  49. if (1 == data)
  50. {
  51. TIMSK &= ~(1 << OCIE1A);
  52. }
  53. outframe = data >> 1;
  54. }
  55. void uart_puts( uint8_t *txt ) // send string
  56. {
  57. while( *txt )
  58. uart_putc ( *txt++ );
  59. }