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

Subversion Repositories neorv32

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

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

powered by: WebSVN 2.1.0

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