-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathkk_uart.c
543 lines (468 loc) · 13.1 KB
/
kk_uart.c
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
/**
* kk_uart.c: A UART (serial port) library for AVR microcontrollers.
* Provides an stdio-compatible `FILE *` handle to the UART, with
* interrupt-driven and buffered receiving (but unbuffered transmitting).
*
* Copyright (c) 2019-2020 Kimmo Kulovesi, https://arkku.dev/
* Provided with absolutely no warranty, use at your own risk only.
* Use and distribute freely, mark modified copies as such.
*/
#include "kk_uart.h"
#ifndef F_CPU
#error F_CPU not defined
#endif
#include <stdbool.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
static char rx_buffer[KK_UART_RECEIVE_BUFFER_SIZE];
typedef uint8_t buffer_index_t;
static volatile buffer_index_t rx_buffer_write = 0;
static volatile buffer_index_t rx_buffer_read = 0;
#define rx_buffer_size ((unsigned int) (sizeof rx_buffer))
#define uart_has_data ((UCSR0A & _BV(RXC0)) != 0)
#define uart_byte UDR0
#define uart_wait_to_read() loop_until_bit_is_set(UCSR0A, RXC0)
#define uart_can_write() bit_is_set(UCSR0A, UDRE0)
#define uart_wait_to_write() loop_until_bit_is_set(UCSR0A, UDRE0)
#define UART_RX_PIN ((uint8_t) 1U)
#define UART_TX_PIN ((uint8_t) 2U)
#define UART_DDR DDRD
#define UART_PORT PORTD
#if KK_UART_RECEIVE_BUFFER_SIZE == 256
#define modulo_rx_buffer_size(x) ((uint8_t) (x))
#elif KK_UART_RECEIVE_BUFFER_SIZE > 256
#error KK_UART_RECEIVE_BUFFER_SIZE too large (max. 256)!
#else
#define modulo_rx_buffer_size(x) ((buffer_index_t) ((x) % rx_buffer_size))
#endif
#if KK_UART_TRANSMIT_BUFFER_SIZE > 0
static char tx_buffer[KK_UART_TRANSMIT_BUFFER_SIZE];
static volatile buffer_index_t tx_buffer_write = 0;
static volatile buffer_index_t tx_buffer_read = 0;
#define tx_buffer_size ((unsigned int) (sizeof tx_buffer))
#if KK_UART_TRANSMIT_BUFFER_SIZE == 256
#define modulo_tx_buffer_size(x) ((uint8_t) (x))
#elif KK_UART_TRANSMIT_BUFFER_SIZE > 256
#error KK_UART_TRANSMIT_BUFFER_SIZE too large (max. 256)!
#else
#define modulo_tx_buffer_size(x) ((buffer_index_t) ((x) % tx_buffer_size))
#endif
#endif
#if KK_UART_CONVERT_CRLF_IN_TO_LF != 0
static bool previous_was_converted_cr = false;
#define IS_END_OF_LINE(b) ((b) == '\n')
#define consume_newline_after_cr(b) do { } while (0)
#else
#define IS_END_OF_LINE(b) ((b) == '\r' || (b) == '\n')
#define consume_newline_after_cr(b) do { if ((b) == '\r') { consume_newline(); } } while (0)
/// Consume a single LF. Used to get rid of the LF of a CRLF pair after
/// the CR has already been consumed. This only tries for a limited time
/// to avoid blocking indefinitely in case the LF is lost or not sent.
static void
consume_newline (void) {
uint_fast8_t attempts = 64;
int c;
do {
c = uart_peekc();
if (c == '\n') {
(void) uart_getc();
return;
}
} while (c == EOF && --attempts);
}
#endif /* KK_UART_CONVERT_CRLF_IN_TO_LF == 0 */
uint8_t
uart_bytes_available (void) {
uint8_t unread_count = modulo_rx_buffer_size(rx_buffer_size + rx_buffer_write - rx_buffer_read);
#if KK_UART_CONVERT_CRLF_IN_TO_LF != 0
if (unread_count && previous_was_converted_cr) {
unread_count -= (rx_buffer[rx_buffer_read] == '\n') ? 1 : 0;
}
#endif
return unread_count;
}
void
uart_flush_unread (void) {
rx_buffer_write = 0;
rx_buffer_read = 0;
#if KK_UART_CONVERT_CRLF_IN_TO_LF != 0
previous_was_converted_cr = false;
#endif
}
#if KK_UART_TRANSMIT_BUFFER_SIZE > 0
#define uart_has_unsent_bytes() (tx_buffer_read != tx_buffer_write)
uint8_t
uart_bytes_unsent (void) {
return modulo_tx_buffer_size(tx_buffer_size + tx_buffer_write - tx_buffer_read);
}
static void
uart_send (const char chr) {
buffer_index_t next_pos;
do {
if (!uart_has_unsent_bytes() && uart_can_write()) {
// Write immediately when we can
uart_byte = chr;
return;
}
next_pos = modulo_tx_buffer_size(tx_buffer_write + 1);
} while (next_pos == tx_buffer_read);
tx_buffer[tx_buffer_write] = chr;
tx_buffer_write = next_pos;
UCSR0B |= _BV(UDRIE0); // Enable interrupt to process tx buffer
}
#ifdef USART_UDRE_vect
ISR(USART_UDRE_vect)
#else
ISR(USART0_UDRE_vect)
#endif
{
const buffer_index_t pos = tx_buffer_read;
if (pos != tx_buffer_write) {
uart_byte = tx_buffer[pos];
tx_buffer_read = modulo_tx_buffer_size(pos + 1);
}
if (tx_buffer_read == tx_buffer_write) {
// No more queued bytes, disable interrupt
UCSR0B &= ~_BV(UDRIE0);
}
}
#else
#define uart_send(chr) do { uart_wait_to_write(); uart_byte = (chr); } while (0)
#endif
int
uart_getc (void) {
char c;
buffer_index_t pos;
#if KK_UART_CONVERT_CRLF_IN_TO_LF != 0
get_next_from_buffer:
#endif
pos = rx_buffer_read;
if (pos == rx_buffer_write) {
return EOF;
}
c = rx_buffer[pos];
rx_buffer_read = modulo_rx_buffer_size(pos + 1);
#if KK_UART_CONVERT_CRLF_IN_TO_LF != 0
if (previous_was_converted_cr) {
previous_was_converted_cr = false;
if (c == '\n') {
goto get_next_from_buffer;
}
}
if (c == '\r') {
previous_was_converted_cr = true;
c = '\n';
}
#endif
return c;
}
int
uart_getc_wait (void) {
int c;
do {
c = uart_getc();
} while (c == EOF); // TODO: Return EOF on break
return c;
}
int
uart_peekc (void) {
#if KK_UART_CONVERT_CRLF_IN_TO_LF != 0
buffer_index_t pos = rx_buffer_read;
if (pos == rx_buffer_write) {
return EOF;
}
char c = rx_buffer[pos];
if (previous_was_converted_cr) {
if (c == '\n') {
pos = modulo_rx_buffer_size(pos + 1);
if (pos == rx_buffer_write) {
return EOF;
}
c = rx_buffer[pos];
}
}
return (c != '\r') ? c : '\n';
#else
return (rx_buffer_read == rx_buffer_write) ? EOF : rx_buffer[rx_buffer_read];
#endif
}
int
uart_peekc_wait (void) {
int c;
do {
c = uart_peekc();
} while (c == EOF); // TODO: Return EOF on break (change callers here to handle it)
return c;
}
void
uart_putc (const char c) {
#if KK_UART_CONVERT_LF_OUT_TO_CRLF != 0
if (c == '\n') {
uart_send('\r');
}
#endif
uart_send(c);
}
void
uart_puts (const char * restrict str) {
char c;
while ((c = *str++)) {
uart_putc(c);
}
}
/// Write the string `pstr` from program space (`PSTR`) to the UART.
void
uart_puts_P (const char * restrict pstr) {
char c;
while ((c = pgm_read_byte(pstr++))) {
uart_putc(c);
}
}
int
uart_consume_line (void) {
int result = 1;
for (;;) {
int c = uart_getc_wait();
if (c == EOF) {
return EOF;
}
switch ((char) c) {
case ' ':
break;
#if KK_UART_CONVERT_CRLF_IN_TO_LF == 0
case '\r':
consume_newline();
#endif
// fallthrough
case '\n':
return result;
case '\t':
break;
default:
if (((uint8_t) c) >= 0x20) {
// There were non-space, non-control characters
result = 0;
}
break;
}
}
}
int
uart_consume_space_and_newlines (void) {
int result = 0;
do {
char c = uart_peekc_wait();
if (!(c == ' ' || IS_END_OF_LINE(c) || c == '\t')) {
break;
}
} while ((result = uart_getc()) != EOF);
return result;
}
int
uart_consume_space (void) {
int result = 0;
do {
int c;
do {
c = uart_peekc();
} while (c == EOF);
if (!(c == ' ' || c == '\t')) {
break;
}
} while ((result = uart_getc()) != EOF);
return result;
}
int
uart_getline (int bufsize, char buf[static bufsize]) {
int c;
int count = 0;
if (bufsize <= 0) {
return -1;
}
--bufsize;
while (count < bufsize) {
c = uart_getc_wait();
if (IS_END_OF_LINE(c) || c == EOF) {
consume_newline_after_cr(c);
break;
}
if (c == '\b' && count) {
// Handle backspace inside the line
--count;
} else if (c >= 0x20 || c == '\t') {
// Only take non-control characters
buf[count++] = c;
}
}
buf[count] = '\0';
return count;
}
int
uart_getword (int bufsize, char buf[static bufsize]) {
int count = 0;
if (bufsize <= 0) {
return -1;
}
--bufsize;
while (count < bufsize) {
char c = uart_peekc_wait(); // TODO: Return on break?
if (c == ' ' || c == '\t') {
if (count) {
break;
}
// Skip leading space
} else if (IS_END_OF_LINE(c)) {
break;
} else if (c == '\b' && count) {
// Handle backspace inside the word
--count;
} else if (c >= 0x20) {
// Don't record control characters
buf[count++] = c;
}
(void) uart_getc();
}
buf[count] = '\0';
return count;
}
long
uart_getlong (int_fast8_t base, int_fast8_t *success) {
bool allow_base_prefix = false;
bool negative = false;
if (base <= 0) {
allow_base_prefix = true;
base = 10;
}
// Skip leading space
(void) uart_consume_space();
unsigned long result = 0;
bool digits_read = false;
for (;;) {
char c = uart_peekc_wait();
if (c >= '0' && c <= '9') {
c -= '0';
if (c < base) {
result *= base;
result += c;
digits_read = true;
} else {
break; // Digit not valid for this base
}
} else if (c == ' ' || IS_END_OF_LINE(c) || c == '\t') {
break;
} else if (c < 0x20) { // Ignore control characters
(void) uart_getc();
continue;
} else if (base > 10) {
c &= ~32; // Convert lowercase to uppercase
c -= 'A';
c += 10;
if (c >= 10 && c < base) {
result *= base;
result += c;
digits_read = true;
} else {
break; // Digit not valid for this base
}
} else if (result == 0) {
if (!digits_read) {
if (c == '-') {
negative = !negative;
} else if (c == '+') {
// No effect, but allow the sign
} else if (allow_base_prefix) {
if (c == '$') {
base = 16;
} else if (c == '%') {
base = 2;
} else {
break;
}
allow_base_prefix = false;
} else {
break;
}
} else if (allow_base_prefix) {
if (c == 'x' || c == 'X') {
// 0x for hexadecimal
base = 16;
} else if (c == 'b') {
// 0b for binary
base = 2;
} else {
break;
}
allow_base_prefix = false;
}
}
(void) uart_getc();
}
if (success) {
*success = digits_read ? base : 0;
}
// Note: This allows overflow on purpose, it is implementation-defined here
// and ok for AVR-GCC (which is the only target of this code). If porting,
// you may wish to check overflow (compare to `LONG_MAX`) before casting.
return negative ? -((long) result) : (long) result;
}
volatile uint8_t uart_last_rx_error = 0;
#ifdef USART_RX_vect
ISR(USART_RX_vect)
#else
ISR(USART0_RX_vect)
#endif
{
uint8_t status = UCSR0A;
char c = uart_byte;
if (status & (_BV(FE0) | _BV(UPE0))) {
uart_last_rx_error = status;
} else {
const buffer_index_t next_pos = modulo_rx_buffer_size(rx_buffer_write + 1);
if (next_pos != rx_buffer_read) {
rx_buffer[rx_buffer_write] = c;
rx_buffer_write = next_pos;
} else {
status |= _BV(DOR0);
}
if (status & _BV(DOR0)) {
uart_last_rx_error = status;
}
}
}
void
uart_init (uint32_t baud, uart_mode_t mode) {
UART_DDR |= UART_TX_PIN;
UART_DDR &= ~UART_RX_PIN;
UART_PORT |= UART_RX_PIN; // Enable pull-up for RX
uint16_t speed = (((uint32_t) F_CPU >> 2) / baud - 1) >> 1;
if (speed < 4096) {
// Ok for 2X mode
UCSR0A |= _BV(U2X0);
} else {
// Must use 1X mode
UCSR0A &= ~(_BV(U2X0));
speed = (((uint32_t) F_CPU >> 3) / baud - 1) >> 1;
}
UBRR0H = speed >> 8;
UBRR0L = speed & 0xFFU;
UCSR0C = (uint8_t) mode; // Mode
UCSR0B = _BV(RXEN0) | _BV(TXEN0); // Enable
UCSR0B |= _BV(RXCIE0); // Receive interrupt enable
}
void
uart_disable (void) {
UCSR0B = 0;
}
static int
getc_uart(FILE *file) {
return uart_getc_wait();
}
static int
putc_uart(char c, FILE *file) {
uart_putc(c);
return 0;
}
/// The serial port UART device.
static FILE uart_fdev = FDEV_SETUP_STREAM((putc_uart), (getc_uart), _FDEV_SETUP_RW);
FILE *uart = &uart_fdev;