95 lines
2.2 KiB
C
95 lines
2.2 KiB
C
#include <zephyr/kernel.h>
|
|
#include <zephyr/device.h>
|
|
#include <zephyr/devicetree.h>
|
|
#include <zephyr/sys/printk.h>
|
|
#include <zephyr/drivers/gpio.h>
|
|
#include <zephyr/drivers/uart.h>
|
|
|
|
// Use the board's chosen console UART
|
|
#define UART_NODE DT_CHOSEN(zephyr_console)
|
|
#define UART_RX_QUEUE_SIZE 16
|
|
|
|
#if !DT_NODE_HAS_STATUS(DT_ALIAS(led0), okay)
|
|
#error "Board does not define alias led0. Add a board overlay"
|
|
#endif
|
|
|
|
static const struct gpio_dt_spec led_red =
|
|
GPIO_DT_SPEC_GET(DT_ALIAS(led0), gpios);
|
|
|
|
#if !DT_NODE_HAS_STATUS(UART_NODE, okay)
|
|
#error "UART console not available. Add a board overlay"
|
|
#endif
|
|
|
|
static const struct device *const uart_dev =
|
|
DEVICE_DT_GET(UART_NODE);
|
|
|
|
/* Do not poll the STM32F4 UART only once per application loop. Its receive
|
|
* data register can hold just one byte, so a second byte causes an overrun.
|
|
* Store received bytes from the UART interrupt until the main thread handles
|
|
* them.
|
|
*/
|
|
K_MSGQ_DEFINE(uart_rx_queue, sizeof(uint8_t), UART_RX_QUEUE_SIZE, 1);
|
|
|
|
static void uart_rx_isr(const struct device *dev, void *user_data) {
|
|
uint8_t ch;
|
|
|
|
ARG_UNUSED(user_data);
|
|
|
|
if (!uart_irq_update(dev) || !uart_irq_rx_ready(dev)) {
|
|
return;
|
|
}
|
|
|
|
while (uart_fifo_read(dev, &ch, 1) == 1) {
|
|
// Drop the newest byte if the application queue is full
|
|
(void)k_msgq_put(&uart_rx_queue, &ch, K_NO_WAIT);
|
|
}
|
|
}
|
|
|
|
int main(void) {
|
|
|
|
uint32_t cnt = 0;
|
|
uint8_t ch;
|
|
int rc;
|
|
|
|
if (!gpio_is_ready_dt(&led_red)) {
|
|
printk("LED GPIO is not ready\r\n");
|
|
return 0;
|
|
}
|
|
|
|
rc = gpio_pin_configure_dt(&led_red, GPIO_OUTPUT_INACTIVE);
|
|
if (rc != 0) {
|
|
printk("Failed to configure LED GPIO: %d\r\n", rc);
|
|
return 0;
|
|
}
|
|
|
|
if (!device_is_ready(uart_dev)) {
|
|
return 0;
|
|
}
|
|
|
|
rc = uart_irq_callback_user_data_set(uart_dev, uart_rx_isr, NULL);
|
|
if (rc != 0) {
|
|
printk("Failed to configure UART RX interrupt: %d\r\n", rc);
|
|
return 0;
|
|
}
|
|
uart_irq_rx_enable(uart_dev);
|
|
|
|
printk("\r\n[UART]: Send O to turn LED on, F to turn it off\r\n");
|
|
|
|
while (1) {
|
|
while (k_msgq_get(&uart_rx_queue, &ch, K_NO_WAIT) == 0) {
|
|
if (ch == 'O' || ch == 'o') {
|
|
gpio_pin_set_dt(&led_red, 1);
|
|
printk("LED on\r\n");
|
|
} else if (ch == 'F' || ch == 'f') {
|
|
gpio_pin_set_dt(&led_red, 0);
|
|
printk("LED off\r\n");
|
|
}
|
|
}
|
|
|
|
printk("Tick: %u\r\n", cnt++);
|
|
k_msleep(200);
|
|
}
|
|
|
|
return 0;
|
|
}
|