semestralka joinig all worlds together
This commit is contained in:
@@ -1,157 +1,92 @@
|
||||
// src/bin/main.rs
|
||||
|
||||
#![no_std]
|
||||
#![no_main]
|
||||
|
||||
use defmt::*;
|
||||
use embassy_executor::Spawner;
|
||||
use embassy_stm32::bind_interrupts;
|
||||
use embassy_stm32::peripherals;
|
||||
use embassy_stm32::peripherals::{PA2, PA3};
|
||||
use embassy_stm32::gpio::{Input, Output, Pull, Speed, Level};
|
||||
use embassy_stm32::Peripherals;
|
||||
use embassy_stm32::usart::{BufferedInterruptHandler, BufferedUart, Config};
|
||||
use embassy_stm32::timer::low_level::Timer as HardwareTimer;
|
||||
use embassy_stm32::interrupt::{self, typelevel::TIM2 as TIM2_IRQ, Priority};
|
||||
use embassy_stm32::peripherals::TIM2;
|
||||
use embedded_io_async::{Read, Write};
|
||||
use embassy_stm32::time::Hertz;
|
||||
use embassy_time::{Timer, Duration, Instant};
|
||||
use embassy_futures::yield_now;
|
||||
use embassy_futures::select::{select, Either};
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use embassy_sync::pipe::Pipe;
|
||||
use embassy_sync::signal::Signal;
|
||||
use embassy_stm32::dma::Request;
|
||||
use embassy_stm32::gpio::{Input, Output, Level, Pull, Speed};
|
||||
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, pipe::Pipe};
|
||||
use embassy_stm32::dma::{TransferOptions, WritableRingBuffer};
|
||||
use dma_gpio::software_uart::{
|
||||
dma_timer::{init_tim6_for_uart, init_tim7_for_uart},
|
||||
gpio_dma_uart_tx::encode_uart_frames,
|
||||
gpio_dma_uart_rx::rx_dma_task,
|
||||
debug::dump_tim6_regs,
|
||||
};
|
||||
use dma_gpio::config::{BAUD, TX_PIN_BIT, RX_OVERSAMPLE, TX_OVERSAMPLE};
|
||||
use dma_gpio::config::{TX_RING_BYTES, RX_RING_BYTES, PIPE_RX_SIZE};
|
||||
use static_cell::StaticCell;
|
||||
use embassy_futures::yield_now;
|
||||
use {defmt_rtt as _, panic_probe as _};
|
||||
use async_uart::safety::{preflight_and_suggest_yield_period, RX_PIPE_CAP, TX_PIPE_CAP};
|
||||
|
||||
static UART_TX: Pipe<CriticalSectionRawMutex, TX_PIPE_CAP> = Pipe::new();
|
||||
static UART_RX: Pipe<CriticalSectionRawMutex, RX_PIPE_CAP> = Pipe::new();
|
||||
static TIM2_TICK: Signal<CriticalSectionRawMutex, ()> = Signal::new();
|
||||
pub const TIM6_UP_REQ: Request = 4;
|
||||
|
||||
bind_interrupts!(
|
||||
struct Irqs {
|
||||
USART1 => BufferedInterruptHandler<peripherals::USART1>;
|
||||
}
|
||||
);
|
||||
|
||||
#[embassy_executor::task]
|
||||
async fn uart_task(mut uart: BufferedUart<'static>) {
|
||||
let mut rx_byte = [0u8; 1];
|
||||
let mut tx_buf = [0u8; 64];
|
||||
loop {
|
||||
// Wait for either RX or TX events.
|
||||
let rx_fut = uart.read(&mut rx_byte);
|
||||
let tx_fut = async {
|
||||
// Until there's outgoing data in TX pipe
|
||||
let n = UART_TX.read(&mut tx_buf).await;
|
||||
n
|
||||
};
|
||||
match select(rx_fut, tx_fut).await {
|
||||
// Incoming data from UART hardware
|
||||
Either::First(res) => {
|
||||
if let Ok(_) = res {
|
||||
// Forward to RX pipe
|
||||
let _ = UART_RX.write(&rx_byte).await;
|
||||
let _ = UART_TX.try_write(&rx_byte);
|
||||
}
|
||||
}
|
||||
// Outgoing data waiting in TX pipe
|
||||
Either::Second(n) => {
|
||||
unwrap!(uart.write(&tx_buf[..n]).await);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
static PIPE_RX: Pipe<CriticalSectionRawMutex, PIPE_RX_SIZE> = Pipe::new();
|
||||
static TX_RING: StaticCell<[u32; TX_RING_BYTES]> = StaticCell::new();
|
||||
static RX_RING: StaticCell<[u8; RX_RING_BYTES]> = StaticCell::new();
|
||||
|
||||
#[embassy_executor::main]
|
||||
async fn main(spawner: Spawner) {
|
||||
info!("tititititi");
|
||||
let p = embassy_stm32::init(Default::default());
|
||||
static TX_BUF: StaticCell<[u8; 256]> = StaticCell::new();
|
||||
static RX_BUF: StaticCell<[u8; 256]> = StaticCell::new();
|
||||
let tx_buf = TX_BUF.init([0; 256]);
|
||||
let rx_buf = RX_BUF.init([0; 256]);
|
||||
let mut cfg = Config::default();
|
||||
cfg.baudrate = 230_400;
|
||||
info!("Hehe");
|
||||
|
||||
// Call preflight and get the computed yield period
|
||||
let yield_period = preflight_and_suggest_yield_period(cfg.baudrate);
|
||||
|
||||
let usart = BufferedUart::new(
|
||||
p.USART1,
|
||||
p.PA10, // RX
|
||||
p.PA9, // TX
|
||||
tx_buf,
|
||||
rx_buf,
|
||||
Irqs,
|
||||
cfg,
|
||||
).unwrap();
|
||||
info!("starting uart task");
|
||||
spawner.spawn(uart_task(usart)).unwrap();
|
||||
|
||||
let mut transfer: u32 = 16;
|
||||
let mut rx_buf = [0u8; 64];
|
||||
let mut last_yield = Instant::now();
|
||||
|
||||
// Software UART bits init
|
||||
let mut tx = Output::new(p.PA2, Level::Low, Speed::Low);
|
||||
let _rx = Input::new(p.PA3, Pull::Up);
|
||||
let _tx = Output::new(p.PA2, Level::High, Speed::VeryHigh);
|
||||
|
||||
let tim = HardwareTimer::new(p.TIM2);
|
||||
init_tim6_for_uart(p.TIM6, BAUD, TX_OVERSAMPLE);
|
||||
init_tim7_for_uart(p.TIM7, BAUD, RX_OVERSAMPLE);
|
||||
|
||||
// Configure for 230_400 Hz
|
||||
tim.set_frequency(Hertz(cfg.baudrate*transfer));
|
||||
tim.enable_update_interrupt(true);
|
||||
tim.start();
|
||||
dump_tim6_regs();
|
||||
|
||||
tx.set_high();
|
||||
loop {
|
||||
// Safe one-time init from StaticCell
|
||||
let rx_ring: &mut [u8; RX_RING_BYTES] = RX_RING.init([0; RX_RING_BYTES]);
|
||||
let tx_ring_mem: &mut [u32; TX_RING_BYTES] = TX_RING.init([0; TX_RING_BYTES]);
|
||||
|
||||
TIM2_TICK.wait().await;
|
||||
tx.set_low();
|
||||
TIM2_TICK.wait().await;
|
||||
// Spawn tasks
|
||||
spawner.spawn(rx_dma_task(p.GPDMA1_CH1, &PIPE_RX, rx_ring).unwrap());
|
||||
|
||||
Timer::after(Duration::from_millis(1000)).await;
|
||||
// Poll RX pipe for new data (non-blocking)
|
||||
if let Ok(n) = UART_RX.try_read(&mut rx_buf) {
|
||||
if n > 0 {
|
||||
if let Ok(s) = core::str::from_utf8(&rx_buf[..n]) {
|
||||
info!("RX got: {}", s);
|
||||
} else {
|
||||
info!("RX got (non‑utf8): {:?}", &rx_buf[..n]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Create and start the TX DMA ring in main.
|
||||
// let bsrr_ptr = embassy_stm32::pac::GPIOA.bsrr().as_ptr() as *mut u32;
|
||||
let odr_ptr = embassy_stm32::pac::GPIOA.odr().as_ptr() as *mut u32;
|
||||
let mut tx_opts = TransferOptions::default();
|
||||
tx_opts.half_transfer_ir = true;
|
||||
tx_opts.complete_transfer_ir = true;
|
||||
|
||||
// Guaranteed to yield before ISR RX buffer can overflow
|
||||
if Instant::now().duration_since(last_yield) >= yield_period {
|
||||
yield_now().await;
|
||||
last_yield = Instant::now();
|
||||
// info!("Yield mf {}", counter);
|
||||
}
|
||||
// Timer::after(Duration::from_micros(1)).await;
|
||||
// Timer::after(Duration::from_secs(5)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[embassy_stm32::interrupt]
|
||||
fn TIM2() {
|
||||
use embassy_stm32::timer::CoreInstance;
|
||||
|
||||
// Access TIM2 core registers directly.
|
||||
let regs = unsafe {
|
||||
embassy_stm32::pac::timer::TimCore::from_ptr(
|
||||
<peripherals::TIM2 as CoreInstance>::regs(),
|
||||
// SAFETY: tx_ring_mem is exclusive
|
||||
let mut tx_ring = unsafe {
|
||||
WritableRingBuffer::new(
|
||||
p.GPDMA1_CH0,
|
||||
TIM6_UP_REQ,
|
||||
odr_ptr,
|
||||
tx_ring_mem,
|
||||
tx_opts,
|
||||
)
|
||||
};
|
||||
// Start DMA
|
||||
tx_ring.start();
|
||||
info!("TX DMA ring started");
|
||||
|
||||
// Clear update flag to avoid retriggering.
|
||||
let sr = regs.sr().read();
|
||||
if sr.uif() {
|
||||
regs.sr().modify(|r| r.set_uif(false));
|
||||
let mut frame_buf = [0u32; 4096];
|
||||
|
||||
// Signal the waiting task that a tick occurred.
|
||||
TIM2_TICK.signal(());
|
||||
loop {
|
||||
info!("tick start");
|
||||
// Timer::after(Duration::from_millis(100)).await;
|
||||
// info!("tick end");
|
||||
let used = encode_uart_frames(
|
||||
TX_PIN_BIT,
|
||||
b"Hello marshmallow\r\n",
|
||||
&mut frame_buf,
|
||||
)
|
||||
.await;
|
||||
|
||||
if used == 0 {
|
||||
info!("encode_uart_frames() produced 0 words, skipping write");
|
||||
yield_now().await;
|
||||
continue;
|
||||
}
|
||||
let _ = tx_ring.write_exact(&frame_buf[..used]).await;
|
||||
info!("text");
|
||||
yield_now().await;
|
||||
}
|
||||
}
|
||||
|
||||
16
semestralka_1/src/config.rs
Normal file
16
semestralka_1/src/config.rs
Normal file
@@ -0,0 +1,16 @@
|
||||
// src/config.rs
|
||||
use crate::software_uart::uart_emulation::{Parity, StopBits, UartConfig};
|
||||
|
||||
pub const BAUD: u32 = 115_200;
|
||||
pub const TX_PIN_BIT: u8 = 2; // PA2
|
||||
pub const TX_OVERSAMPLE: u16 = 1;
|
||||
pub const RX_OVERSAMPLE: u16 = 16;
|
||||
pub const RX_RING_BYTES: usize = 4096;
|
||||
pub const TX_RING_BYTES: usize = 4096;
|
||||
pub const PIPE_RX_SIZE: usize = 256;
|
||||
|
||||
pub const UART_CFG: UartConfig = UartConfig {
|
||||
data_bits: 8,
|
||||
parity: Parity::None,
|
||||
stop_bits: StopBits::One,
|
||||
};
|
||||
@@ -1,3 +1,4 @@
|
||||
#![no_std]
|
||||
pub mod safety;
|
||||
// pub mod software_uart;
|
||||
|
||||
pub mod software_uart;
|
||||
pub mod config;
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
// src/safety.rs
|
||||
use defmt::info;
|
||||
use embassy_time::Duration;
|
||||
|
||||
// ISR RX ring capacity = RX_BUF len
|
||||
const ISR_RX_BUF_CAP: usize = 256;
|
||||
// Yield 1/2 the time it takes to fill ISR RX ring.
|
||||
const YIELD_MARGIN_NUM: u32 = 1;
|
||||
const YIELD_MARGIN_DEN: u32 = 2;
|
||||
// Ensure RX_PIPE_CAP can hold this.
|
||||
const WORST_MAIN_LATENCY_MS: u32 = 20;
|
||||
|
||||
pub const TX_PIPE_CAP: usize = 1024;
|
||||
pub const RX_PIPE_CAP: usize = 1024;
|
||||
|
||||
|
||||
|
||||
/// Perform safety checks and compute yield timing to avoid buffer overflow.
|
||||
///
|
||||
/// # Panics
|
||||
/// Panics if pipe capacities are too small for the configured baud.
|
||||
pub fn preflight_and_suggest_yield_period(baud: u32) -> Duration {
|
||||
// Approx bytes per second for 8N1 (10 bits per byte on the wire)
|
||||
let bytes_per_sec = (baud / 10).max(1);
|
||||
|
||||
// Time until ISR RX ring fills, in microseconds.
|
||||
let t_fill_us = (ISR_RX_BUF_CAP as u64) * 1_000_000u64 / (bytes_per_sec as u64);
|
||||
|
||||
// Choose a yield period as a fraction of t_fill.
|
||||
let yield_us = (t_fill_us as u64)
|
||||
.saturating_mul(YIELD_MARGIN_NUM as u64)
|
||||
/ (YIELD_MARGIN_DEN as u64);
|
||||
|
||||
// Verify RX pipe can absorb a worst-case app latency so uart_task
|
||||
// can always forward without dropping when it runs.
|
||||
let required_rx_pipe = (bytes_per_sec as u64) * (WORST_MAIN_LATENCY_MS as u64) / 1000;
|
||||
|
||||
if (RX_PIPE_CAP as u64) < required_rx_pipe {
|
||||
core::panic!(
|
||||
"RX pipe too small: have {}B, need >= {}B for {}ms at {} bps",
|
||||
RX_PIPE_CAP, required_rx_pipe, WORST_MAIN_LATENCY_MS, baud
|
||||
);
|
||||
}
|
||||
|
||||
info!(
|
||||
"Preflight: baud={}, rx_isr={}B, rx_pipe={}B, bytes/s={}, t_fill_us={}, yield_us={}",
|
||||
baud,
|
||||
ISR_RX_BUF_CAP,
|
||||
RX_PIPE_CAP,
|
||||
bytes_per_sec,
|
||||
t_fill_us,
|
||||
yield_us
|
||||
);
|
||||
|
||||
// Never choose zero.
|
||||
Duration::from_micros(yield_us.max(1) as u64)
|
||||
}
|
||||
BIN
semestralka_1/src/software_uart/.gpio_dma_uart_tx.rs.swp
Normal file
BIN
semestralka_1/src/software_uart/.gpio_dma_uart_tx.rs.swp
Normal file
Binary file not shown.
43
semestralka_1/src/software_uart/debug.rs
Normal file
43
semestralka_1/src/software_uart/debug.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
// src/software_uart/debug.rs
|
||||
use defmt::info;
|
||||
|
||||
pub fn dump_tim6_regs() {
|
||||
use embassy_stm32::pac::timer::TimBasic;
|
||||
let tim = unsafe { TimBasic::from_ptr(0x4000_1000usize as _) };
|
||||
let sr = tim.sr().read();
|
||||
let dier = tim.dier().read();
|
||||
let cr1 = tim.cr1().read();
|
||||
let arr = tim.arr().read().arr();
|
||||
let psc = tim.psc().read();
|
||||
info!(
|
||||
"TIM6: CR1.CEN={} DIER.UDE={} SR.UIF={} PSC={} ARR={}",
|
||||
cr1.cen(),
|
||||
dier.ude(),
|
||||
sr.uif(),
|
||||
psc,
|
||||
arr
|
||||
);
|
||||
}
|
||||
|
||||
pub fn dump_dma_ch0_regs() {
|
||||
use embassy_stm32::pac::gpdma::Gpdma;
|
||||
let dma = unsafe { Gpdma::from_ptr(0x4002_0000usize as _) };
|
||||
let ch = dma.ch(0);
|
||||
let cr = ch.cr().read();
|
||||
let tr1 = ch.tr1().read();
|
||||
let tr2 = ch.tr2().read();
|
||||
let br1 = ch.br1().read();
|
||||
info!(
|
||||
"GPDMA1_CH0: EN={} PRIO={} SDW={} DDW={} SINC={} DINC={} REQSEL={} SWREQ={} DREQ={} BNDT={}",
|
||||
cr.en(),
|
||||
cr.prio(),
|
||||
tr1.sdw(),
|
||||
tr1.ddw(),
|
||||
tr1.sinc(),
|
||||
tr1.dinc(),
|
||||
tr2.reqsel(),
|
||||
tr2.swreq(),
|
||||
tr2.dreq(),
|
||||
br1.bndt()
|
||||
);
|
||||
}
|
||||
58
semestralka_1/src/software_uart/dma_timer.rs
Normal file
58
semestralka_1/src/software_uart/dma_timer.rs
Normal file
@@ -0,0 +1,58 @@
|
||||
// src/dma_timer.rs
|
||||
|
||||
use embassy_stm32::{
|
||||
peripherals::{TIM6, TIM7},
|
||||
rcc,
|
||||
timer::low_level::Timer,
|
||||
Peri,
|
||||
};
|
||||
use core::mem;
|
||||
use embassy_stm32::timer::BasicInstance;
|
||||
use embassy_stm32::pac::timer::vals::Urs;
|
||||
|
||||
/// Initializes TIM6 to tick at `baud * oversample` frequency.
|
||||
/// Each TIM6 update event triggers one DMA beat.
|
||||
pub fn init_tim6_for_uart<'d>(tim6: Peri<'d, TIM6>, baud: u32, oversample: u16) {
|
||||
rcc::enable_and_reset::<TIM6>();
|
||||
let ll = Timer::new(tim6);
|
||||
configure_basic_timer(&ll, baud, oversample);
|
||||
mem::forget(ll);
|
||||
}
|
||||
|
||||
/// Initializes TIM7 to tick at `baud * oversample` frequency.
|
||||
/// Each TIM7 update event triggers one DMA beat.
|
||||
pub fn init_tim7_for_uart<'d>(tim7: Peri<'d, TIM7>, baud: u32, oversample: u16) {
|
||||
rcc::enable_and_reset::<TIM7>();
|
||||
let ll = Timer::new(tim7);
|
||||
configure_basic_timer(&ll, baud, oversample);
|
||||
mem::forget(ll);
|
||||
}
|
||||
|
||||
// Shared internal helper — identical CR1/ARR setup
|
||||
fn configure_basic_timer<T: BasicInstance>(ll: &Timer<'_, T>, baud: u32, oversample: u16) {
|
||||
let f_timer = rcc::frequency::<T>().0;
|
||||
let target = baud.saturating_mul(oversample.max(1) as u32).max(1);
|
||||
|
||||
// Compute ARR (prescaler = 0)
|
||||
let mut arr = (f_timer / target).saturating_sub(1) as u16;
|
||||
if arr == 0 { arr = 1; }
|
||||
|
||||
ll.regs_basic().cr1().write(|w| {
|
||||
w.set_cen(false);
|
||||
w.set_opm(false);
|
||||
w.set_udis(false);
|
||||
w.set_urs(Urs::ANY_EVENT);
|
||||
});
|
||||
|
||||
ll.regs_basic().psc().write_value(0u16);
|
||||
ll.regs_basic().arr().write(|w| w.set_arr(arr));
|
||||
ll.regs_basic().dier().modify(|w| w.set_ude(true));
|
||||
ll.regs_basic().egr().write(|w| w.set_ug(true));
|
||||
|
||||
ll.regs_basic().cr1().write(|w| {
|
||||
w.set_opm(false);
|
||||
w.set_cen(true);
|
||||
w.set_udis(false);
|
||||
w.set_urs(Urs::ANY_EVENT);
|
||||
});
|
||||
}
|
||||
44
semestralka_1/src/software_uart/gpio_dma_uart_rx.rs
Normal file
44
semestralka_1/src/software_uart/gpio_dma_uart_rx.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
// src/software_uart/runtime.rs
|
||||
use embassy_executor::task;
|
||||
use embassy_stm32::{
|
||||
dma::Request,
|
||||
peripherals::GPDMA1_CH1,
|
||||
Peri,
|
||||
};
|
||||
use embassy_stm32::dma::{
|
||||
ReadableRingBuffer,
|
||||
TransferOptions,
|
||||
};
|
||||
use crate::config::{RX_OVERSAMPLE, UART_CFG};
|
||||
use crate::software_uart::decode_uart_samples;
|
||||
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, pipe::Pipe};
|
||||
use embassy_futures::yield_now;
|
||||
|
||||
// datasheet tabulka 137
|
||||
pub const TIM7_UP_REQ: Request = 5;
|
||||
|
||||
/// RX DMA task: reads GPIO samples paced by TIM7 and fills PIPE_RX
|
||||
#[task]
|
||||
pub async fn rx_dma_task(
|
||||
ch: Peri<'static, GPDMA1_CH1>,
|
||||
pipe_rx: &'static Pipe<CriticalSectionRawMutex, 256>,
|
||||
ring: &'static mut [u8],
|
||||
) {
|
||||
let gpioa_idr = embassy_stm32::pac::GPIOA.idr().as_ptr() as *mut u8;
|
||||
|
||||
let mut opts = TransferOptions::default();
|
||||
opts.half_transfer_ir = true;
|
||||
opts.complete_transfer_ir = true;
|
||||
|
||||
// SAFETY: ring is exclusive to this task
|
||||
let mut rx = unsafe { ReadableRingBuffer::new(ch, TIM7_UP_REQ, gpioa_idr, ring, opts) };
|
||||
rx.start();
|
||||
|
||||
let mut chunk = [0u8; 256];
|
||||
loop {
|
||||
let _ = rx.read_exact(&mut chunk).await;
|
||||
let decoded = decode_uart_samples(&chunk, RX_OVERSAMPLE, &UART_CFG);
|
||||
pipe_rx.write(&decoded).await;
|
||||
yield_now().await;
|
||||
}
|
||||
}
|
||||
75
semestralka_1/src/software_uart/gpio_dma_uart_tx.rs
Normal file
75
semestralka_1/src/software_uart/gpio_dma_uart_tx.rs
Normal file
@@ -0,0 +1,75 @@
|
||||
// src/software_uart/gpio_dma_uart_tx.rs
|
||||
use embassy_executor::task;
|
||||
use embassy_stm32::{
|
||||
dma::{Request, TransferOptions, WritableRingBuffer},
|
||||
peripherals::GPDMA1_CH0,
|
||||
Peri,
|
||||
};
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use embassy_sync::pipe::Pipe;
|
||||
use embassy_futures::yield_now;
|
||||
use defmt::info;
|
||||
|
||||
use crate::config::{TX_OVERSAMPLE, TX_PIN_BIT, UART_CFG};
|
||||
use crate::software_uart::dma_timer::init_tim6_for_uart;
|
||||
use crate::software_uart::uart_emulation::encode_uart_byte_cfg;
|
||||
|
||||
pub const TIM6_UP_REQ: Request = 4;
|
||||
|
||||
pub async fn encode_uart_frames<'a>(
|
||||
pin_bit: u8,
|
||||
bytes: &[u8],
|
||||
out_buf: &'a mut [u32],
|
||||
) -> usize {
|
||||
let mut offset = 0;
|
||||
for &b in bytes {
|
||||
let mut frame = [0u32; 12];
|
||||
let used = encode_uart_byte_cfg(pin_bit, b, &UART_CFG, &mut frame);
|
||||
|
||||
if offset + used <= out_buf.len() {
|
||||
out_buf[offset..offset + used].copy_from_slice(&frame[..used]);
|
||||
offset += used;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
|
||||
// cooperative async yield
|
||||
yield_now().await;
|
||||
}
|
||||
offset
|
||||
}
|
||||
|
||||
/// TX DMA task: encodes UART frames and sends them via DMA at TIM6 rate
|
||||
#[task]
|
||||
pub async fn tx_dma_task(
|
||||
ch: Peri<'static, GPDMA1_CH0>,
|
||||
odr_ptr: *mut u32,
|
||||
tx_ring: &'static mut [u32],
|
||||
) {
|
||||
let mut opts = TransferOptions::default();
|
||||
opts.half_transfer_ir = true;
|
||||
opts.complete_transfer_ir = true;
|
||||
|
||||
// SAFETY: tx_ring is exclusive to this task
|
||||
let mut tx = unsafe { WritableRingBuffer::new(ch, TIM6_UP_REQ, odr_ptr, tx_ring, opts) };
|
||||
tx.start();
|
||||
info!("TX DMA ring started");
|
||||
|
||||
let mut frame_buf = [0u32; 4096];
|
||||
|
||||
loop {
|
||||
info!("TX task tick");
|
||||
|
||||
let used = encode_uart_frames(TX_PIN_BIT, b"Hello marshmallow\r\n", &mut frame_buf).await;
|
||||
|
||||
if used == 0 {
|
||||
info!("encode_uart_frames() produced 0 words, skipping write");
|
||||
yield_now().await;
|
||||
continue;
|
||||
}
|
||||
|
||||
let _ = tx.write_exact(&frame_buf[..used]).await;
|
||||
|
||||
yield_now().await;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,13 @@
|
||||
// src/software_uart/mod.rs
|
||||
|
||||
pub mod suart;
|
||||
pub use suart::*;
|
||||
pub mod gpio_dma_uart_tx;
|
||||
pub mod gpio_dma_uart_rx;
|
||||
pub mod dma_timer;
|
||||
pub mod uart_emulation;
|
||||
pub mod debug;
|
||||
|
||||
pub use gpio_dma_uart_tx::*;
|
||||
pub use gpio_dma_uart_rx::*;
|
||||
pub use dma_timer::*;
|
||||
pub use uart_emulation::*;
|
||||
pub use debug::*;
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
// src/software_uart/suart.rs
|
||||
|
||||
use embassy_stm32::peripherals::{PA2, PA3};
|
||||
use embassy_stm32::gpio::{Input, Output, Pull, Speed, Level};
|
||||
use embassy_stm32::Peripherals;
|
||||
use embassy_time::Timer;
|
||||
|
||||
pub async fn suart_test(mut tx_pin: PA2, rx_pin: PA3) {
|
||||
let mut tx = Output::new(tx_pin.into(), Level::Low, Speed::Low);
|
||||
let _rx = Input::new(rx_pin.into(), Pull::Up);
|
||||
|
||||
loop {
|
||||
tx.set_high();
|
||||
Timer::after_millis(500).await;
|
||||
|
||||
tx.set_low();
|
||||
Timer::after_millis(500).await;
|
||||
}
|
||||
}
|
||||
151
semestralka_1/src/software_uart/uart_emulation.rs
Normal file
151
semestralka_1/src/software_uart/uart_emulation.rs
Normal file
@@ -0,0 +1,151 @@
|
||||
// src/software_uart/uart_emulation.rs
|
||||
use heapless::Vec;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Parity {
|
||||
None,
|
||||
Even,
|
||||
Odd,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum StopBits {
|
||||
One,
|
||||
Two,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct UartConfig {
|
||||
pub data_bits: u8,
|
||||
pub parity: Parity,
|
||||
pub stop_bits: StopBits,
|
||||
}
|
||||
|
||||
impl Default for UartConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
data_bits: 8,
|
||||
parity: Parity::None,
|
||||
stop_bits: StopBits::One,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes one byte into a sequence of GPIO BSRR words
|
||||
pub fn encode_uart_byte_cfg(
|
||||
pin_bit: u8,
|
||||
data: u8,
|
||||
cfg: &UartConfig,
|
||||
out: &mut [u32; 12],
|
||||
) -> usize {
|
||||
// GPIOx_BSRR register str. 636 kap. 13.4.7
|
||||
let set_high = |bit: u8| -> u32 { 1u32 << bit };
|
||||
let set_low = |bit: u8| -> u32 { 0 };
|
||||
// let set_low = |bit: u8| -> u32 { 1u32 << (bit as u32 + 16) };
|
||||
|
||||
let mut idx = 0usize;
|
||||
|
||||
// START bit (LOW)
|
||||
out[idx] = set_low(pin_bit);
|
||||
idx += 1;
|
||||
|
||||
// Data bits, LSB-first
|
||||
let nbits = cfg.data_bits.clamp(5, 8);
|
||||
for i in 0..nbits {
|
||||
let one = ((data >> i) & 1) != 0;
|
||||
out[idx] = if one { set_high(pin_bit) } else { set_low(pin_bit) };
|
||||
idx += 1;
|
||||
}
|
||||
|
||||
// Parity
|
||||
match cfg.parity {
|
||||
Parity::None => {}
|
||||
Parity::Even | Parity::Odd => {
|
||||
let mask: u8 = if nbits == 8 { 0xFF } else { (1u16 << nbits) as u8 - 1 };
|
||||
let ones = (data & mask).count_ones() & 1;
|
||||
let par_bit_is_one = match cfg.parity {
|
||||
Parity::Even => ones == 1,
|
||||
Parity::Odd => ones == 0,
|
||||
_ => false,
|
||||
};
|
||||
out[idx] = if par_bit_is_one {
|
||||
set_high(pin_bit)
|
||||
} else {
|
||||
set_low(pin_bit)
|
||||
};
|
||||
idx += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// STOP bits (HIGH)
|
||||
let stop_ticks = match cfg.stop_bits {
|
||||
StopBits::One => 1usize,
|
||||
StopBits::Two => 2usize,
|
||||
};
|
||||
for _ in 0..stop_ticks {
|
||||
out[idx] = set_high(pin_bit);
|
||||
idx += 1;
|
||||
}
|
||||
|
||||
idx
|
||||
}
|
||||
|
||||
/// Decode an oversampled stream of logic levels into UART bytes.
|
||||
pub fn decode_uart_samples(
|
||||
samples: &[u8],
|
||||
oversample: u16,
|
||||
cfg: &UartConfig,
|
||||
) -> heapless::Vec<u8, 256> {
|
||||
|
||||
let mut out = Vec::<u8, 256>::new();
|
||||
let mut idx = 0usize;
|
||||
let nbits = cfg.data_bits as usize;
|
||||
|
||||
while idx + (oversample as usize * (nbits + 3)) < samples.len() {
|
||||
// Wait for start bit (falling edge: high -> low)
|
||||
if samples[idx] != 0 && samples[idx + 1] == 0 {
|
||||
// Align to middle of start bit
|
||||
idx += (oversample / 2) as usize;
|
||||
|
||||
// Sanity check start bit really low
|
||||
if samples.get(idx).copied().unwrap_or(1) != 0 {
|
||||
idx += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Sample data bits
|
||||
let mut data: u8 = 0;
|
||||
for bit in 0..nbits {
|
||||
idx += oversample as usize;
|
||||
let bit_val = samples
|
||||
.get(idx)
|
||||
.map(|&b| if b != 0 { 1u8 } else { 0u8 })
|
||||
.unwrap_or(1);
|
||||
data |= bit_val << bit;
|
||||
}
|
||||
|
||||
// Parity: skip / verify
|
||||
match cfg.parity {
|
||||
Parity::None => {}
|
||||
Parity::Even | Parity::Odd => {
|
||||
idx += oversample as usize;
|
||||
// You can optionally add parity check here if needed
|
||||
}
|
||||
}
|
||||
|
||||
// Move past stop bits
|
||||
let stop_skip = match cfg.stop_bits {
|
||||
StopBits::One => oversample as usize,
|
||||
StopBits::Two => (oversample * 2) as usize,
|
||||
};
|
||||
idx += stop_skip;
|
||||
|
||||
// Push decoded byte
|
||||
let _ = out.push(data);
|
||||
} else {
|
||||
idx += 1;
|
||||
}
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
Reference in New Issue
Block a user