working tx

This commit is contained in:
2026-03-13 12:45:14 +01:00
parent 5af462ac4f
commit 62baffe992
7 changed files with 341 additions and 34 deletions

View File

@@ -5,17 +5,91 @@
const struct device *test_uart = DEVICE_DT_GET(DT_ALIAS(testuart));
// TEST GENERATED CODE START
#include <zephyr/sys/ring_buffer.h>
#include <zephyr/spinlock.h>
#define RX_BUF_SIZE 256
#define TX_BUF_SIZE 256
RING_BUF_DECLARE(rx_buf, RX_BUF_SIZE);
RING_BUF_DECLARE(tx_buf, TX_BUF_SIZE);
static struct k_spinlock uart_lock;
static void uart_isr(const struct device *dev, void *user_data)
{
uart_irq_update(dev);
if (uart_irq_rx_ready(dev)) {
uint8_t byte;
while (uart_fifo_read(dev, &byte, 1) == 1) {
k_spinlock_key_t key = k_spin_lock(&uart_lock);
ring_buf_put(&rx_buf, &byte, 1);
k_spin_unlock(&uart_lock, key);
}
}
if (uart_irq_tx_ready(dev)) {
uint8_t byte;
k_spinlock_key_t key = k_spin_lock(&uart_lock);
if (ring_buf_get(&tx_buf, &byte, 1) == 1) {
k_spin_unlock(&uart_lock, key);
uart_fifo_fill(dev, &byte, 1);
} else {
k_spin_unlock(&uart_lock, key);
uart_irq_tx_disable(dev); // nothing left, stop firing
}
}
}
/* Call once at init */
void uart_init(const struct device *dev)
{
uart_irq_callback_set(dev, uart_isr);
uart_irq_rx_enable(dev);
/* TX IRQ is enabled on demand when we have data to send */
}
/* Write bytes to TX — call from thread context */
int uart_write(const struct device *dev, const uint8_t *data, size_t len)
{
k_spinlock_key_t key = k_spin_lock(&uart_lock);
uint32_t written = ring_buf_put(&tx_buf, data, len);
k_spin_unlock(&uart_lock, key);
uart_irq_tx_enable(dev); // kick off TX if not already running
return written;
}
/* Read bytes from RX — call from thread context */
int uart_read(const struct device *dev, uint8_t *data, size_t len)
{
k_spinlock_key_t key = k_spin_lock(&uart_lock);
uint32_t read = ring_buf_get(&rx_buf, data, len);
k_spin_unlock(&uart_lock, key);
return read;
}
// TEST GENERATED CODE END
int main(void) {
const char msg [] = "Hello World";
const uint8_t msg [] = "Hello World\r\n";
uart_irq_callback_set(test_uart, uart_isr);
while (1) {
for (char c : msg) {
uart_poll_out(test_uart, c);
}
uart_write(test_uart, msg, sizeof(msg));
k_sleep(K_MSEC(100));
k_thread_runtime_stats_t stats;
k_thread_runtime_stats_all_get(&stats);
uint8_t buff[32];
sprintf((char*)&buff, "total cycles: %15llu\r\n", stats.execution_cycles);
uart_write(test_uart, buff, sizeof(buff));
k_sleep(K_MSEC(1000));
}
return 0;
}