uart.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. This file is part of the ChipWhisperer Example Targets
  3. Copyright (C) 2017 NewAE Technology Inc.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include "sam4l_hal.h"
  16. void usart0_reset(void)
  17. {
  18. /* Disable the Write Protect. */
  19. USART0->US_WPMR = US_WPMR_WPKEY(0x555341U);
  20. /* Reset registers that could cause unpredictable behavior after reset. */
  21. USART0->US_MR = 0;
  22. USART0->US_RTOR = 0;
  23. USART0->US_TTGR = 0;
  24. /* Disable TX and RX. */
  25. USART0->US_CR = US_CR_RSTRX | US_CR_RXDIS;
  26. USART0->US_CR = US_CR_RSTTX | US_CR_TXDIS;
  27. /* Reset status bits. */
  28. USART0->US_CR = US_CR_RSTSTA;
  29. }
  30. void uart0_init(void)
  31. {
  32. /* Turn on clocks! */
  33. periclk_usart0_init();
  34. /* Reset the USART and shut down TX and RX. */
  35. usart0_reset();
  36. /* 7.3728 MHz clock, 38400 baud. See table 24-7 in SAM4L Datasheet */
  37. USART0->US_BRGR = (12 << US_BRGR_CD_Pos);
  38. USART0->US_MR |= (US_MR_USART_MODE_NORMAL | US_MR_CHRL_8_BIT | US_MR_PAR_NO | US_MR_NBSTOP_1_BIT | US_MR_CHMODE_NORMAL);
  39. USART0->US_CR = US_CR_TXEN;
  40. USART0->US_CR = US_CR_RXEN;
  41. GPIO->GPIO_PORT[0].GPIO_GPERC = GPIO_PA12A_USART0_TXD;
  42. GPIO->GPIO_PORT[0].GPIO_GPERC = GPIO_PA11A_USART0_RXD;
  43. }
  44. void uart0_putch(char c)
  45. {
  46. while(!(USART0->US_CSR & US_CSR_TXRDY));
  47. USART0->US_THR = US_THR_TXCHR(c);
  48. }
  49. char uart0_getch(void)
  50. {
  51. while(!(USART0->US_CSR & US_CSR_RXRDY));
  52. return USART0->US_RHR & US_RHR_RXCHR_Msk;
  53. }