summaryrefslogtreecommitdiffstats
path: root/app/usart.c
blob: 8d982874ec8050427ecacff0d2ad78f911232d47 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include "project.h"

#define BUFFER_SIZE 256


#define USART1_TX GPIO_USART1_TX
#define USART1_TX_PORT GPIOA
#define USART1_RX GPIO_USART1_RX
#define USART1_RX_PORT GPIOA


ring_t rx1_ring;
static uint8_t rx1_ring_buf[BUFFER_SIZE];

ring_t tx1_ring;
static uint8_t tx1_ring_buf[BUFFER_SIZE];

void
usart1_isr (void)
{
  uint8_t data;

  /* Check if we were called because of RXNE. */
  if (((USART_CR1 (USART1) & USART_CR1_RXNEIE) != 0) &&
      ((USART_SR (USART1) & USART_SR_RXNE) != 0)) {

    /* Retrieve the data from the peripheral. */
    data = usart_recv (USART1);


    ring_write_byte (&rx1_ring, data);
  }

  /* Check if we were called because of TXE. */
  if (((USART_CR1 (USART1) & USART_CR1_TXEIE) != 0) &&
      ((USART_SR (USART1) & USART_SR_TXE) != 0)) {

    if (ring_read_byte (&tx1_ring, &data)) {
      /*No more data, Disable the TXE interrupt, it's no longer needed. */
      USART_CR1 (USART1) &= ~USART_CR1_TXEIE;
    } else
      usart_send (USART1, data);
  }

}


int
_write (int file, char *ptr, int len)
{
  int ret;

  if (file == 1) {
    ret = len;

    usart1_drain();

    while (len--) {
      if (*ptr == '\n')
        ring_write_byte (&tx1_ring, '\r');

      ring_write_byte (&tx1_ring, * (ptr++));
    }

    USART_CR1 (USART1) |= USART_CR1_TXEIE;
    return ret;
  }

  errno = EIO;
  return -1;
}

void
usart1_queue (uint8_t d)
{
  ring_write_byte (&tx1_ring, d);
  USART_CR1 (USART1) |= USART_CR1_TXEIE;
}


void
usart1_drain (void)
{
  while (!ring_empty (&tx1_ring));
}



void
usart_init (void)
{
  rcc_periph_clock_enable (RCC_USART1);

  ring_init (&rx1_ring, rx1_ring_buf, sizeof (rx1_ring_buf));
  ring_init (&tx1_ring, tx1_ring_buf, sizeof (tx1_ring_buf));

  /* Enable the USART1,2 interrupt. */
  nvic_enable_irq (NVIC_USART1_IRQ);

  /* Map pins, and usart1 to have pull ups */
  MAP_AF_PP (USART1_TX);
  MAP_INPUT_PU (USART1_RX);


  /* Setup UART1 parameters. */
  usart_set_baudrate (USART1, 115200);
  usart_set_databits (USART1, 8);
  usart_set_stopbits (USART1, USART_STOPBITS_1);
  usart_set_parity (USART1, USART_PARITY_NONE);
  usart_set_flow_control (USART1, USART_FLOWCONTROL_NONE);
  usart_set_mode (USART1, USART_MODE_TX_RX);


  /* Enable USART1 Receive interrupt. */
  USART_CR1 (USART1) |= USART_CR1_RXNEIE;

  /* Finally enable the USARTs. */
  usart_enable (USART1);
}