|
| 1 | +/* |
| 2 | + * Copyright (c) 2016 Linaro |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +#include <zephyr.h> |
| 18 | +#include <uart.h> |
| 19 | +#include <drivers/console/uart_console.h> |
| 20 | +#include <misc/printk.h> |
| 21 | +#include "zephyr_getchar.h" |
| 22 | + |
| 23 | +static struct nano_sem uart_sem; |
| 24 | +#define UART_BUFSIZE 256 |
| 25 | +static uint8_t uart_ringbuf[UART_BUFSIZE]; |
| 26 | +static uint8_t i_get, i_put; |
| 27 | + |
| 28 | +static int console_irq_input_hook(struct device *dev, uint8_t ch) |
| 29 | +{ |
| 30 | + int i_next = (i_put + 1) & (UART_BUFSIZE - 1); |
| 31 | + if (i_next == i_get) { |
| 32 | + printk("UART buffer overflow - char dropped\n"); |
| 33 | + return 1; |
| 34 | + } |
| 35 | + uart_ringbuf[i_put] = ch; |
| 36 | + i_put = i_next; |
| 37 | + //printk("%x\n", ch); |
| 38 | + nano_isr_sem_give(&uart_sem); |
| 39 | + return 1; |
| 40 | +} |
| 41 | + |
| 42 | +uint8_t zephyr_getchar(void) { |
| 43 | + nano_task_sem_take(&uart_sem, TICKS_UNLIMITED); |
| 44 | + unsigned int key = irq_lock(); |
| 45 | + uint8_t c = uart_ringbuf[i_get++]; |
| 46 | + i_get &= UART_BUFSIZE - 1; |
| 47 | + irq_unlock(key); |
| 48 | + return c; |
| 49 | +} |
| 50 | + |
| 51 | +void zephyr_getchar_init(void) { |
| 52 | + nano_sem_init(&uart_sem); |
| 53 | + struct device *uart_console_dev = device_get_binding(CONFIG_UART_CONSOLE_ON_DEV_NAME); |
| 54 | + uart_irq_input_hook_set(uart_console_dev, console_irq_input_hook); |
| 55 | + // All NULLs because we're interested only in the callback above |
| 56 | + uart_register_input(NULL, NULL, NULL); |
| 57 | +} |
0 commit comments