uart2.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //uart2.c
  2. #include "uart2.h"
  3. #include <avr/io.h>
  4. #include <avr/interrupt.h>
  5. #include <avr/pgmspace.h>
  6. #include "rbuf.h"
  7. #define UART2_BAUD 115200
  8. #define UART_BAUD_SELECT(baudRate,xtalCpu) (((float)(xtalCpu))/(((float)(baudRate))*8.0)-1.0+0.5)
  9. #define uart2_rxcomplete (UCSR2A & (1 << RXC2))
  10. #define uart2_txcomplete (UCSR2A & (1 << TXC2))
  11. #define uart2_txready (UCSR2A & (1 << UDRE2))
  12. uint8_t uart2_ibuf[10] = {0, 0};
  13. FILE _uart2io = {0};
  14. int uart2_putchar(char c, FILE *stream)
  15. {
  16. while (!uart2_txready);
  17. UDR2 = c; // transmit byte
  18. // while (!uart2_txcomplete); // wait until byte sent
  19. // UCSR2A |= (1 << TXC2); // delete TXCflag
  20. return 0;
  21. }
  22. int uart2_getchar(FILE *stream)
  23. {
  24. if (rbuf_empty(uart2_ibuf)) return -1;
  25. return rbuf_get(uart2_ibuf);
  26. }
  27. void uart2_init(void)
  28. {
  29. rbuf_ini(uart2_ibuf, 6);
  30. UCSR2A |= (1 << U2X2); // baudrate multiplier
  31. UBRR2L = UART_BAUD_SELECT(UART2_BAUD, F_CPU); // select baudrate
  32. UCSR2B = (1 << RXEN2) | (1 << TXEN2); // enable receiver and transmitter
  33. UCSR2B |= (1 << RXCIE2); // enable rx interrupt
  34. fdev_setup_stream(uart2io, uart2_putchar, uart2_getchar, _FDEV_SETUP_WRITE | _FDEV_SETUP_READ); //setup uart2 i/o stream
  35. }
  36. void uart2_rx_clr(void)
  37. {
  38. rbuf_w(uart2_ibuf) = 0;
  39. rbuf_r(uart2_ibuf) = 0;
  40. }
  41. uint8_t uart2_rx_ok(void)
  42. {
  43. //printf_P(PSTR("uart2_rx_ok %hhu %hhu %hhu %hhu %hhu %hhu %hhu %hhu %hhu %hhu\n"), uart2_ibuf[0], uart2_ibuf[1], uart2_ibuf[2], uart2_ibuf[3], uart2_ibuf[4], uart2_ibuf[5], uart2_ibuf[6], uart2_ibuf[7], uart2_ibuf[8], uart2_ibuf[9]);
  44. // return 0;
  45. // _lock(); //lock
  46. uint8_t i = rbuf_w(uart2_ibuf); //get write index
  47. // _unlock(); //unlock
  48. uint8_t e = rbuf_l(uart2_ibuf) - 1; //get end index
  49. // printf_P(PSTR("%d %d \n"), i, e);
  50. // return 0;
  51. if ((i--) == 255) i = e; //decrement index
  52. if ((uart2_ibuf[4 + i] != '\n') &&
  53. (uart2_ibuf[4 + i] != '\r')) return 0; //no match - exit
  54. if ((i--) == 255) i = e; //decrement index
  55. if (uart2_ibuf[4 + i] != 'k') return 0; //no match - exit
  56. if ((i--) == 255) i = e; //decrement index
  57. if (uart2_ibuf[4 + i] != 'o') return 0; //no match - exit
  58. uart2_ibuf[4 + i] = 0; //discard char
  59. return 1; //match "ok\n"
  60. }
  61. ISR(USART2_RX_vect)
  62. {
  63. //printf_P(PSTR("USART2_RX_vect \n") );
  64. if (rbuf_put(uart2_ibuf, UDR2) < 0) // put received byte to buffer
  65. {
  66. //rx buffer full
  67. }
  68. }