OpenCores
URL https://opencores.org/ocsvn/neorv32/neorv32/trunk

Subversion Repositories neorv32

[/] [neorv32/] [trunk/] [sw/] [lib/] [source/] [neorv32_uart.c] - Blame information for rev 22

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 2 zero_gravi
// #################################################################################################
2
// # << NEORV32: neorv32_uart.c - Universal Asynchronous Receiver/Transmitter (UART) HW Driver >>  #
3
// # ********************************************************************************************* #
4
// # BSD 3-Clause License                                                                          #
5
// #                                                                                               #
6
// # Copyright (c) 2020, Stephan Nolting. All rights reserved.                                     #
7
// #                                                                                               #
8
// # Redistribution and use in source and binary forms, with or without modification, are          #
9
// # permitted provided that the following conditions are met:                                     #
10
// #                                                                                               #
11
// # 1. Redistributions of source code must retain the above copyright notice, this list of        #
12
// #    conditions and the following disclaimer.                                                   #
13
// #                                                                                               #
14
// # 2. Redistributions in binary form must reproduce the above copyright notice, this list of     #
15
// #    conditions and the following disclaimer in the documentation and/or other materials        #
16
// #    provided with the distribution.                                                            #
17
// #                                                                                               #
18
// # 3. Neither the name of the copyright holder nor the names of its contributors may be used to  #
19
// #    endorse or promote products derived from this software without specific prior written      #
20
// #    permission.                                                                                #
21
// #                                                                                               #
22
// # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS   #
23
// # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF               #
24
// # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE    #
25
// # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,     #
26
// # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE #
27
// # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED    #
28
// # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING     #
29
// # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED  #
30
// # OF THE POSSIBILITY OF SUCH DAMAGE.                                                            #
31
// # ********************************************************************************************* #
32
// # The NEORV32 Processor - https://github.com/stnolting/neorv32              (c) Stephan Nolting #
33
// #################################################################################################
34
 
35
 
36
/**********************************************************************//**
37
 * @file neorv32_uart.c
38
 * @author Stephan Nolting
39
 * @brief Universal asynchronous receiver/transmitter (UART) HW driver source file.
40
 *
41
 * @note These functions should only be used if the UART unit was synthesized (IO_UART_USE = true).
42
 **************************************************************************/
43
 
44
#include "neorv32.h"
45
#include "neorv32_uart.h"
46
#include <string.h>
47
 
48
/// \cond
49
// Private functions
50
static void __neorv32_uart_itoa(uint32_t x, char *res) __attribute__((unused)); // GCC: do not ouput a warning when this variable is unused
51
static void __neorv32_uart_tohex(uint32_t x, char *res) __attribute__((unused)); // GCC: do not ouput a warning when this variable is unused
52
/// \endcond
53
 
54
 
55
/**********************************************************************//**
56
 * Check if UART unit was synthesized.
57
 *
58
 * @return 0 if UART was not synthesized, 1 if UART is available.
59
 **************************************************************************/
60
int neorv32_uart_available(void) {
61
 
62 12 zero_gravi
  if (SYSINFO_FEATURES & (1 << SYSINFO_FEATURES_IO_UART)) {
63 2 zero_gravi
    return 1;
64
  }
65
  else {
66
    return 0;
67
  }
68
}
69
 
70
 
71
/**********************************************************************//**
72
 * Enable and configure UART.
73
 *
74
 * @param[in] baudrate Targeted BAUD rate (e.g. 9600).
75
 * @param[in] rx_irq Enable RX interrupt (data received) when 1.
76
 * @param[in] tx_irq Enable TX interrupt (transmission done) when 1.
77
 **************************************************************************/
78
void neorv32_uart_setup(uint32_t baudrate, uint8_t rx_irq, uint8_t tx_irq) {
79
 
80
  UART_CT = 0; // reset
81
 
82
  // raw baud rate prescaler
83 12 zero_gravi
  uint32_t clock = SYSINFO_CLK;
84 2 zero_gravi
  uint16_t i = 0; // BAUD rate divisor
85
  uint8_t p = 0; // prsc = CLK/2
86
  while (clock >= 2*baudrate) {
87
    clock -= 2*baudrate;
88
    i++;
89
  }
90
 
91
  // find clock prsc
92
  while (i >= 0x0fff) {
93
    if ((p == 2) || (p == 4))
94
      i >>= 3;
95
    else
96
      i >>= 1;
97
    p++;
98
  }
99
 
100
  uint32_t prsc = (uint32_t)p;
101
  prsc = prsc << UART_CT_PRSC0;
102
 
103
  uint32_t baud = (uint32_t)i;
104
  baud = baud << UART_CT_BAUD00;
105
 
106
  uint32_t uart_en = 1;
107
  uart_en = uart_en << UART_CT_EN;
108
 
109
  uint32_t rx_irq_en = (uint32_t)(rx_irq & 1);
110
  rx_irq_en = rx_irq_en << UART_CT_RX_IRQ;
111
 
112
  uint32_t tx_irq_en = (uint32_t)(tx_irq & 1);
113
  tx_irq_en = tx_irq_en << UART_CT_TX_IRQ;
114
 
115
  UART_CT = prsc | baud | uart_en | rx_irq_en | tx_irq_en;
116
}
117
 
118
 
119
/**********************************************************************//**
120
 * Disable UART.
121
 **************************************************************************/
122
void neorv32_uart_disable(void) {
123
 
124
  UART_CT &= ~((uint32_t)(1 << UART_CT_EN));
125
}
126
 
127
 
128
 
129
/**********************************************************************//**
130
 * Send single char via UART.
131
 *
132
 * @note This function is blocking.
133 4 zero_gravi
 * @warning The 'DEVNULL_UART_OVERRIDE' compiler user flag will forward all UART TX data to the DEVNULL simulation console output.
134 2 zero_gravi
 *
135
 * @param[in] c Char to be send.
136
 **************************************************************************/
137
void neorv32_uart_putc(char c) {
138
 
139 3 zero_gravi
#ifdef DEVNULL_UART_OVERRIDE
140
  #warning UART OVERRIDE! Sending all UART.TX data to DEVNULL simulation output instead of UART transmitter. Use this for simulations only!
141
  DEVNULL_DATA = (uint32_t)c;
142
#else
143 2 zero_gravi
  // wait for previous transfer to finish
144
  while ((UART_CT & (1<<UART_CT_TX_BUSY)) != 0);
145
  UART_DATA = ((uint32_t)c) << UART_DATA_LSB;
146 3 zero_gravi
#endif
147
 
148 2 zero_gravi
}
149
 
150
 
151
/**********************************************************************//**
152
 * Get char from UART.
153
 *
154
 * @note This function is blocking.
155
 *
156
 * @return Received char.
157
 **************************************************************************/
158
char neorv32_uart_getc(void) {
159
 
160
  uint32_t d = 0;
161
  while (1) {
162
    d = UART_DATA;
163
    if ((d & (1<<UART_DATA_AVAIL)) != 0) { // char received?
164
      return (char)d;
165
    }
166
  }
167
}
168
 
169
 
170
/**********************************************************************//**
171
 * Check if UARt has received a char.
172
 *
173
 * @note This function is non-blocking.
174
 * @note Use neorv32_uart_char_received_get(void) to get the char.
175
 *
176
 * @return =!0 when a char has been received.
177
 **************************************************************************/
178
int neorv32_uart_char_received(void) {
179
 
180
  if ((UART_DATA & (1<<UART_DATA_AVAIL)) != 0) {
181
    return 1;
182
  }
183
  else {
184
    return 0;
185
  }
186
}
187
 
188
 
189
/**********************************************************************//**
190
 * Get a received char.
191
 *
192
 * @note This function is non-blocking.
193
 * @note Should only be used in combination with neorv32_uart_char_received(void).
194
 *
195
 * @return Received char.
196
 **************************************************************************/
197
char neorv32_uart_char_received_get(void) {
198
 
199
  return (char)UART_DATA;
200
}
201
 
202
 
203
/**********************************************************************//**
204
 * Print string (zero-terminated) via UART. Print full line break "\r\n" for every '\n'.
205
 *
206
 * @note This function is blocking.
207
 *
208
 * @param[in] s Pointer to string.
209
 **************************************************************************/
210 22 zero_gravi
void neorv32_uart_print(const char *s) {
211 2 zero_gravi
 
212
  char c = 0;
213
  while ((c = *s++)) {
214
    if (c == '\n') {
215
      neorv32_uart_putc('\r');
216
    }
217
    neorv32_uart_putc(c);
218
  }
219
}
220
 
221
 
222
/**********************************************************************//**
223
 * Private function for 'neorv32_printf' to convert into decimal.
224
 *
225
 * @param[in] x Unsigned input number.
226
 * @param[in,out] res Pointer for storing the reuslting number string (11 chars).
227
 **************************************************************************/
228
static void __neorv32_uart_itoa(uint32_t x, char *res) {
229
 
230 22 zero_gravi
  static const char numbers[] = "0123456789";
231 2 zero_gravi
  char buffer1[11];
232
  uint16_t i, j;
233
 
234
  buffer1[10] = '\0';
235
  res[10] = '\0';
236
 
237
  // convert
238
  for (i=0; i<10; i++) {
239
    buffer1[i] = numbers[x%10];
240
    x /= 10;
241
  }
242
 
243
  // delete 'leading' zeros
244
  for (i=9; i!=0; i--) {
245
    if (buffer1[i] == '0')
246
      buffer1[i] = '\0';
247
    else
248
      break;
249
  }
250
 
251
  // reverse
252
  j = 0;
253
  do {
254
    if (buffer1[i] != '\0')
255
      res[j++] = buffer1[i];
256
  } while (i--);
257
 
258
  res[j] = '\0'; // terminate result string
259
}
260
 
261
 
262
/**********************************************************************//**
263
 * Private function for 'neorv32_printf' to convert into hexadecimal.
264
 *
265
 * @param[in] x Unsigned input number.
266
 * @param[in,out] res Pointer for storing the reuslting number string (9 chars).
267
 **************************************************************************/
268
static void __neorv32_uart_tohex(uint32_t x, char *res) {
269
 
270 22 zero_gravi
  static const char symbols[] = "0123456789abcdef";
271 2 zero_gravi
 
272
  int i;
273
  for (i=0; i<8; i++) { // nibble by bibble
274
    uint32_t num_tmp = x >> (4*i);
275
    res[7-i] = (char)symbols[num_tmp & 0x0f];
276
  }
277
 
278
  res[8] = '\0'; // terminate result string
279
}
280
 
281
 
282
/**********************************************************************//**
283
 * Custom version of 'printf' function.
284
 *
285
 * @note This function is blocking.
286
 *
287
 * @param[in] format Pointer to format string.
288
 *
289
 * <TABLE>
290
 * <TR><TD>%s</TD><TD>String (array of chars, zero-terminated)</TD></TR>
291
 * <TR><TD>%c</TD><TD>Single char</TD></TR>
292
 * <TR><TD>%i</TD><TD>32-bit signed number, printed as decimal</TD></TR>
293
 * <TR><TD>%u</TD><TD>32-bit unsigned number, printed as decimal</TD></TR>
294
 * <TR><TD>%x</TD><TD>32-bit number, printed as 8-char hexadecimal</TD></TR>
295
 * </TABLE>
296
 **************************************************************************/
297 22 zero_gravi
void neorv32_uart_printf(const char *format, ...) {
298 2 zero_gravi
 
299
  char c, string_buf[11];
300
  int32_t n;
301
 
302
  va_list a;
303
  va_start(a, format);
304
 
305
  while ((c = *format++)) {
306
    if (c == '%') {
307
      c = *format++;
308
      switch (c) {
309
        case 's': // string
310
          neorv32_uart_print(va_arg(a, char*));
311
          break;
312
        case 'c': // char
313
          neorv32_uart_putc((char)va_arg(a, int));
314
          break;
315
        case 'i': // 32-bit signed
316
          n = (int32_t)va_arg(a, int32_t);
317
          if (n < 0) {
318
            n = -n;
319
            neorv32_uart_putc('-');
320
          }
321
          __neorv32_uart_itoa((uint32_t)n, string_buf);
322
          neorv32_uart_print(string_buf);
323
          break;
324
        case 'u': // 32-bit unsigned
325
          __neorv32_uart_itoa(va_arg(a, uint32_t), string_buf);
326
          neorv32_uart_print(string_buf);
327
          break;
328
        case 'x': // 32-bit hexadecimal
329
          __neorv32_uart_tohex(va_arg(a, uint32_t), string_buf);
330
          neorv32_uart_print(string_buf);
331
          break;
332
        default:
333
          return;
334
      }
335
    }
336
    else {
337
      if (c == '\n') {
338
        neorv32_uart_putc('\r');
339
      }
340
      neorv32_uart_putc(c);
341
    }
342
  }
343
  va_end(a);
344
}
345
 
346
 
347
/**********************************************************************//**
348
 * Simplified custom version of 'scanf' function.
349
 *
350
 * @note This function is blocking.
351
 *
352
 * @param[in,out] buffer Pointer to array of chars to store string.
353
 * @param[in] max_size Maximum number of chars to sample.
354
 * @param[in] echo Echo UART input when 1.
355
 * @return Number of chars read.
356
 **************************************************************************/
357
int neorv32_uart_scan(char *buffer, int max_size, int echo) {
358
 
359
  char c = 0;
360
  int length = 0;
361
 
362
  while (1) {
363
    c = neorv32_uart_getc();
364
    if (c == '\b') { // BACKSPACE
365
      if (length != 0) {
366
        if (echo) {
367
          neorv32_uart_print("\b \b"); // delete last char in console
368
        }
369
        buffer--;
370
        length--;
371
      }
372
    }
373
    else if (c == '\r') // carriage return
374
      break;
375
    else if ((c >= ' ') && (c <= '~') && (length < (max_size-1))) {
376
      if (echo) {
377
        neorv32_uart_putc(c); // echo
378
      }
379
      *buffer++ = c;
380
      length++;
381
    }
382
  }
383
  *buffer = '\0'; // terminate string
384
 
385
  return length;
386
}
387
 

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.