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

Subversion Repositories neorv32

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

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 44 zero_gravi
// # Copyright (c) 2021, Stephan Nolting. All rights reserved.                                     #
7 2 zero_gravi
// #                                                                                               #
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 44 zero_gravi
 * @note These functions should only be used if the UART unit was synthesized (IO_UART_EN = true).
42 2 zero_gravi
 **************************************************************************/
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 47 zero_gravi
 * @note The 'UART_SIM_MODE' compiler flag will configure UART for simulation mode: all UART TX data will be redirected to simulation output. Use this for simulations only!
75
 * @note To enable simulation mode add <USER_FLAGS+=-DUART_SIM_MODE> when compiling.
76 30 zero_gravi
 *
77 47 zero_gravi
 * @warning The baud rate is computed using INTEGER operations (truncation errors might occur).
78
 *
79 2 zero_gravi
 * @param[in] baudrate Targeted BAUD rate (e.g. 9600).
80 42 zero_gravi
 * @param[in] parity PArity configuration (00=off, 10=even, 11=odd).
81 2 zero_gravi
 **************************************************************************/
82 48 zero_gravi
void neorv32_uart_setup(uint32_t baudrate, uint8_t parity) {
83 2 zero_gravi
 
84
  UART_CT = 0; // reset
85
 
86 12 zero_gravi
  uint32_t clock = SYSINFO_CLK;
87 2 zero_gravi
  uint16_t i = 0; // BAUD rate divisor
88 36 zero_gravi
  uint8_t p = 0; // initial prsc = CLK/2
89
 
90
  // raw clock prescaler
91
#ifdef __riscv_div
92
  // use div instructions
93
  i = (uint16_t)(clock / (2*baudrate));
94
#else
95
  // division via repeated subtraction
96 2 zero_gravi
  while (clock >= 2*baudrate) {
97
    clock -= 2*baudrate;
98
    i++;
99
  }
100 36 zero_gravi
#endif
101 2 zero_gravi
 
102 47 zero_gravi
  // find baud prescaler (12-bit wide))
103 2 zero_gravi
  while (i >= 0x0fff) {
104
    if ((p == 2) || (p == 4))
105
      i >>= 3;
106
    else
107
      i >>= 1;
108
    p++;
109
  }
110
 
111 47 zero_gravi
  uint32_t clk_prsc = (uint32_t)p;
112
  clk_prsc = clk_prsc << UART_CT_PRSC0;
113 2 zero_gravi
 
114 47 zero_gravi
  uint32_t baud_prsc = (uint32_t)i;
115
  baud_prsc = baud_prsc - 1;
116
  baud_prsc = baud_prsc << UART_CT_BAUD00;
117 2 zero_gravi
 
118
  uint32_t uart_en = 1;
119
  uart_en = uart_en << UART_CT_EN;
120
 
121 42 zero_gravi
  uint32_t parity_config = (uint32_t)(parity & 3);
122
  parity_config = parity_config << UART_CT_PMODE0;
123
 
124 30 zero_gravi
  /* Enable the UART for SIM mode. */
125 42 zero_gravi
  /* USE THIS ONLY FOR SIMULATION! */
126 30 zero_gravi
#ifdef UART_SIM_MODE
127 35 zero_gravi
  #warning UART_SIM_MODE enabled! Sending all UART.TX data to text.io simulation output instead of real UART transmitter. Use this for simulations only!
128 30 zero_gravi
  uint32_t sim_mode = 1 << UART_CT_SIM_MODE;
129
#else
130
  uint32_t sim_mode = 0;
131
#endif
132
 
133 48 zero_gravi
  UART_CT = clk_prsc | baud_prsc | uart_en | parity_config | sim_mode;
134 2 zero_gravi
}
135
 
136
 
137
/**********************************************************************//**
138
 * Disable UART.
139
 **************************************************************************/
140
void neorv32_uart_disable(void) {
141
 
142
  UART_CT &= ~((uint32_t)(1 << UART_CT_EN));
143
}
144
 
145
 
146
/**********************************************************************//**
147
 * Send single char via UART.
148
 *
149
 * @note This function is blocking.
150
 *
151
 * @param[in] c Char to be send.
152
 **************************************************************************/
153
void neorv32_uart_putc(char c) {
154
 
155 30 zero_gravi
#ifdef UART_SIM_MODE
156
  UART_DATA = ((uint32_t)c) << UART_DATA_LSB;
157 3 zero_gravi
#else
158 2 zero_gravi
  // wait for previous transfer to finish
159
  while ((UART_CT & (1<<UART_CT_TX_BUSY)) != 0);
160
  UART_DATA = ((uint32_t)c) << UART_DATA_LSB;
161 3 zero_gravi
#endif
162 2 zero_gravi
}
163
 
164
 
165
/**********************************************************************//**
166 23 zero_gravi
 * Check if UART TX is busy.
167
 *
168
 * @note This function is blocking.
169
 *
170
 * @return 0 if idle, 1 if busy
171
 **************************************************************************/
172
int neorv32_uart_tx_busy(void) {
173
 
174
  if ((UART_CT & (1<<UART_CT_TX_BUSY)) != 0) {
175
    return 1;
176
  }
177
  return 0;
178
}
179
 
180
 
181
/**********************************************************************//**
182 2 zero_gravi
 * Get char from UART.
183
 *
184 42 zero_gravi
 * @note This function is blocking and does not check for UART frame/parity errors.
185 2 zero_gravi
 *
186
 * @return Received char.
187
 **************************************************************************/
188
char neorv32_uart_getc(void) {
189
 
190
  uint32_t d = 0;
191
  while (1) {
192
    d = UART_DATA;
193
    if ((d & (1<<UART_DATA_AVAIL)) != 0) { // char received?
194
      return (char)d;
195
    }
196
  }
197
}
198
 
199
 
200
/**********************************************************************//**
201 42 zero_gravi
 * Get char from UART (and check errors).
202 2 zero_gravi
 *
203 42 zero_gravi
 * @note This function is non-blocking and checks for frame and parity errors.
204
 *
205
 * @param[in,out] data Received char.
206
 * @return Status code (0=nothing received, 1: char received without errors; -1: char received with frame error; -2: char received with parity error; -3 char received with frame & parity error).
207
 **************************************************************************/
208
int neorv32_uart_getc_secure(char *data) {
209
 
210
  uint32_t uart_rx = UART_DATA;
211
  if (uart_rx & (1<<UART_DATA_AVAIL)) { // char available at all?
212
 
213
    int status = 0;
214
 
215
    // check for frame error
216
    if (uart_rx & (1<<UART_DATA_FERR)) {
217
      status -= 1;
218
    }
219
 
220
    // check for parity error
221
    if (uart_rx & (1<<UART_DATA_PERR)) {
222
      status -= 2;
223
    }
224
 
225
    if (status == 0) {
226
      status = 1;
227
    }
228
 
229
    // get received byte
230
    *data =  (char)uart_rx;
231
 
232
    return status;
233
  }
234
  else {
235
    return 0;
236
  }
237
}
238
 
239
 
240
/**********************************************************************//**
241
 * Check if UART has received a char.
242
 *
243 2 zero_gravi
 * @note This function is non-blocking.
244
 * @note Use neorv32_uart_char_received_get(void) to get the char.
245
 *
246
 * @return =!0 when a char has been received.
247
 **************************************************************************/
248
int neorv32_uart_char_received(void) {
249
 
250
  if ((UART_DATA & (1<<UART_DATA_AVAIL)) != 0) {
251
    return 1;
252
  }
253
  else {
254
    return 0;
255
  }
256
}
257
 
258
 
259
/**********************************************************************//**
260
 * Get a received char.
261
 *
262
 * @note This function is non-blocking.
263
 * @note Should only be used in combination with neorv32_uart_char_received(void).
264
 *
265
 * @return Received char.
266
 **************************************************************************/
267
char neorv32_uart_char_received_get(void) {
268
 
269
  return (char)UART_DATA;
270
}
271
 
272
 
273
/**********************************************************************//**
274
 * Print string (zero-terminated) via UART. Print full line break "\r\n" for every '\n'.
275
 *
276
 * @note This function is blocking.
277
 *
278
 * @param[in] s Pointer to string.
279
 **************************************************************************/
280 22 zero_gravi
void neorv32_uart_print(const char *s) {
281 2 zero_gravi
 
282
  char c = 0;
283
  while ((c = *s++)) {
284
    if (c == '\n') {
285
      neorv32_uart_putc('\r');
286
    }
287
    neorv32_uart_putc(c);
288
  }
289
}
290
 
291
 
292
/**********************************************************************//**
293
 * Private function for 'neorv32_printf' to convert into decimal.
294
 *
295
 * @param[in] x Unsigned input number.
296
 * @param[in,out] res Pointer for storing the reuslting number string (11 chars).
297
 **************************************************************************/
298
static void __neorv32_uart_itoa(uint32_t x, char *res) {
299
 
300 22 zero_gravi
  static const char numbers[] = "0123456789";
301 2 zero_gravi
  char buffer1[11];
302
  uint16_t i, j;
303
 
304
  buffer1[10] = '\0';
305
  res[10] = '\0';
306
 
307
  // convert
308
  for (i=0; i<10; i++) {
309
    buffer1[i] = numbers[x%10];
310
    x /= 10;
311
  }
312
 
313
  // delete 'leading' zeros
314
  for (i=9; i!=0; i--) {
315
    if (buffer1[i] == '0')
316
      buffer1[i] = '\0';
317
    else
318
      break;
319
  }
320
 
321
  // reverse
322
  j = 0;
323
  do {
324
    if (buffer1[i] != '\0')
325
      res[j++] = buffer1[i];
326
  } while (i--);
327
 
328
  res[j] = '\0'; // terminate result string
329
}
330
 
331
 
332
/**********************************************************************//**
333
 * Private function for 'neorv32_printf' to convert into hexadecimal.
334
 *
335
 * @param[in] x Unsigned input number.
336
 * @param[in,out] res Pointer for storing the reuslting number string (9 chars).
337
 **************************************************************************/
338
static void __neorv32_uart_tohex(uint32_t x, char *res) {
339
 
340 22 zero_gravi
  static const char symbols[] = "0123456789abcdef";
341 2 zero_gravi
 
342
  int i;
343
  for (i=0; i<8; i++) { // nibble by bibble
344
    uint32_t num_tmp = x >> (4*i);
345
    res[7-i] = (char)symbols[num_tmp & 0x0f];
346
  }
347
 
348
  res[8] = '\0'; // terminate result string
349
}
350
 
351
 
352
/**********************************************************************//**
353
 * Custom version of 'printf' function.
354
 *
355
 * @note This function is blocking.
356
 *
357
 * @param[in] format Pointer to format string.
358
 *
359
 * <TABLE>
360
 * <TR><TD>%s</TD><TD>String (array of chars, zero-terminated)</TD></TR>
361
 * <TR><TD>%c</TD><TD>Single char</TD></TR>
362
 * <TR><TD>%i</TD><TD>32-bit signed number, printed as decimal</TD></TR>
363
 * <TR><TD>%u</TD><TD>32-bit unsigned number, printed as decimal</TD></TR>
364
 * <TR><TD>%x</TD><TD>32-bit number, printed as 8-char hexadecimal</TD></TR>
365
 * </TABLE>
366
 **************************************************************************/
367 22 zero_gravi
void neorv32_uart_printf(const char *format, ...) {
368 2 zero_gravi
 
369
  char c, string_buf[11];
370
  int32_t n;
371
 
372
  va_list a;
373
  va_start(a, format);
374
 
375
  while ((c = *format++)) {
376
    if (c == '%') {
377
      c = *format++;
378
      switch (c) {
379
        case 's': // string
380
          neorv32_uart_print(va_arg(a, char*));
381
          break;
382
        case 'c': // char
383
          neorv32_uart_putc((char)va_arg(a, int));
384
          break;
385
        case 'i': // 32-bit signed
386
          n = (int32_t)va_arg(a, int32_t);
387
          if (n < 0) {
388
            n = -n;
389
            neorv32_uart_putc('-');
390
          }
391
          __neorv32_uart_itoa((uint32_t)n, string_buf);
392
          neorv32_uart_print(string_buf);
393
          break;
394
        case 'u': // 32-bit unsigned
395
          __neorv32_uart_itoa(va_arg(a, uint32_t), string_buf);
396
          neorv32_uart_print(string_buf);
397
          break;
398
        case 'x': // 32-bit hexadecimal
399
          __neorv32_uart_tohex(va_arg(a, uint32_t), string_buf);
400
          neorv32_uart_print(string_buf);
401
          break;
402
        default:
403
          return;
404
      }
405
    }
406
    else {
407
      if (c == '\n') {
408
        neorv32_uart_putc('\r');
409
      }
410
      neorv32_uart_putc(c);
411
    }
412
  }
413
  va_end(a);
414
}
415
 
416
 
417
/**********************************************************************//**
418
 * Simplified custom version of 'scanf' function.
419
 *
420
 * @note This function is blocking.
421
 *
422
 * @param[in,out] buffer Pointer to array of chars to store string.
423
 * @param[in] max_size Maximum number of chars to sample.
424
 * @param[in] echo Echo UART input when 1.
425
 * @return Number of chars read.
426
 **************************************************************************/
427
int neorv32_uart_scan(char *buffer, int max_size, int echo) {
428
 
429
  char c = 0;
430
  int length = 0;
431
 
432
  while (1) {
433
    c = neorv32_uart_getc();
434
    if (c == '\b') { // BACKSPACE
435
      if (length != 0) {
436
        if (echo) {
437
          neorv32_uart_print("\b \b"); // delete last char in console
438
        }
439
        buffer--;
440
        length--;
441
      }
442
    }
443
    else if (c == '\r') // carriage return
444
      break;
445
    else if ((c >= ' ') && (c <= '~') && (length < (max_size-1))) {
446
      if (echo) {
447
        neorv32_uart_putc(c); // echo
448
      }
449
      *buffer++ = c;
450
      length++;
451
    }
452
  }
453
  *buffer = '\0'; // terminate string
454
 
455
  return length;
456
}
457
 

powered by: WebSVN 2.1.0

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