From 303f160e9423247f571adf56866c3c5f6ccca325 Mon Sep 17 00:00:00 2001 From: riceman2000 Date: Thu, 7 Aug 2025 23:36:13 -0400 Subject: [PATCH 1/2] Add examples for wiznet devboard --- examples/rp235x/Cargo.toml | 2 +- .../rp235x/src/bin/ethernet_w5500_icmp.rs | 143 ++++++++++++++++++ .../src/bin/ethernet_w5500_icmp_ping.rs | 134 ++++++++++++++++ .../src/bin/ethernet_w5500_multisocket.rs | 139 +++++++++++++++++ .../src/bin/ethernet_w5500_tcp_client.rs | 127 ++++++++++++++++ .../src/bin/ethernet_w5500_tcp_server.rs | 136 +++++++++++++++++ examples/rp235x/src/bin/ethernet_w5500_udp.rs | 116 ++++++++++++++ 7 files changed, 796 insertions(+), 1 deletion(-) create mode 100644 examples/rp235x/src/bin/ethernet_w5500_icmp.rs create mode 100644 examples/rp235x/src/bin/ethernet_w5500_icmp_ping.rs create mode 100644 examples/rp235x/src/bin/ethernet_w5500_multisocket.rs create mode 100644 examples/rp235x/src/bin/ethernet_w5500_tcp_client.rs create mode 100644 examples/rp235x/src/bin/ethernet_w5500_tcp_server.rs create mode 100644 examples/rp235x/src/bin/ethernet_w5500_udp.rs diff --git a/examples/rp235x/Cargo.toml b/examples/rp235x/Cargo.toml index eecd98894..2a4e888d9 100644 --- a/examples/rp235x/Cargo.toml +++ b/examples/rp235x/Cargo.toml @@ -12,7 +12,7 @@ embassy-executor = { version = "0.8.0", path = "../../embassy-executor", feature embassy-time = { version = "0.4.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } embassy-rp = { version = "0.7.0", path = "../../embassy-rp", features = ["defmt", "unstable-pac", "time-driver", "critical-section-impl", "rp235xa", "binary-info"] } embassy-usb = { version = "0.5.0", path = "../../embassy-usb", features = ["defmt"] } -embassy-net = { version = "0.7.0", path = "../../embassy-net", features = ["defmt", "tcp", "udp", "raw", "dhcpv4", "medium-ethernet", "dns"] } +embassy-net = { version = "0.7.0", path = "../../embassy-net", features = ["defmt", "icmp", "tcp", "udp", "raw", "dhcpv4", "medium-ethernet", "dns"] } embassy-net-wiznet = { version = "0.2.0", path = "../../embassy-net-wiznet", features = ["defmt"] } embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } embassy-usb-logger = { version = "0.5.0", path = "../../embassy-usb-logger" } diff --git a/examples/rp235x/src/bin/ethernet_w5500_icmp.rs b/examples/rp235x/src/bin/ethernet_w5500_icmp.rs new file mode 100644 index 000000000..f1abd311c --- /dev/null +++ b/examples/rp235x/src/bin/ethernet_w5500_icmp.rs @@ -0,0 +1,143 @@ +//! This example implements an echo (ping) with an ICMP Socket and using defmt to report the results. +//! +//! Although there is a better way to execute pings using the child module ping of the icmp module, +//! this example allows for other icmp messages like `Destination unreachable` to be sent aswell. +//! +//! Example written for the [`WIZnet W5500-EVB-Pico2`](https://docs.wiznet.io/Product/iEthernet/W5500/w5500-evb-pico2) board. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_futures::yield_now; +use embassy_net::icmp::{ChecksumCapabilities, IcmpEndpoint, IcmpSocket, Icmpv4Packet, Icmpv4Repr, PacketMetadata}; +use embassy_net::{Stack, StackResources}; +use embassy_net_wiznet::chip::W5500; +use embassy_net_wiznet::*; +use embassy_rp::clocks::RoscRng; +use embassy_rp::gpio::{Input, Level, Output, Pull}; +use embassy_rp::peripherals::SPI0; +use embassy_rp::spi::{Async, Config as SpiConfig, Spi}; +use embassy_time::{Delay, Instant, Timer}; +use embedded_hal_bus::spi::ExclusiveDevice; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +type ExclusiveSpiDevice = ExclusiveDevice, Output<'static>, Delay>; + +#[embassy_executor::task] +async fn ethernet_task(runner: Runner<'static, W5500, ExclusiveSpiDevice, Input<'static>, Output<'static>>) -> ! { + runner.run().await +} + +#[embassy_executor::task] +async fn net_task(mut runner: embassy_net::Runner<'static, Device<'static>>) -> ! { + runner.run().await +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let mut rng = RoscRng; + + let mut spi_cfg = SpiConfig::default(); + spi_cfg.frequency = 50_000_000; + let (miso, mosi, clk) = (p.PIN_16, p.PIN_19, p.PIN_18); + let spi = Spi::new(p.SPI0, clk, mosi, miso, p.DMA_CH0, p.DMA_CH1, spi_cfg); + let cs = Output::new(p.PIN_17, Level::High); + let w5500_int = Input::new(p.PIN_21, Pull::Up); + let w5500_reset = Output::new(p.PIN_20, Level::High); + + let mac_addr = [0x02, 0x00, 0x00, 0x00, 0x00, 0x00]; + static STATE: StaticCell> = StaticCell::new(); + let state = STATE.init(State::<8, 8>::new()); + let (device, runner) = embassy_net_wiznet::new( + mac_addr, + state, + ExclusiveDevice::new(spi, cs, Delay), + w5500_int, + w5500_reset, + ) + .await + .unwrap(); + unwrap!(spawner.spawn(ethernet_task(runner))); + + // Generate random seed + let seed = rng.next_u64(); + + // Init network stack + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new( + device, + embassy_net::Config::dhcpv4(Default::default()), + RESOURCES.init(StackResources::new()), + seed, + ); + + // Launch network task + unwrap!(spawner.spawn(net_task(runner))); + + info!("Waiting for DHCP..."); + let cfg = wait_for_config(stack).await; + let local_addr = cfg.address.address(); + info!("IP address: {:?}", local_addr); + + // Then we can use it! + let mut rx_buffer = [0; 256]; + let mut tx_buffer = [0; 256]; + let mut rx_meta = [PacketMetadata::EMPTY]; + let mut tx_meta = [PacketMetadata::EMPTY]; + + // Identifier used for the ICMP socket + let ident = 42; + + // Create and bind the socket + let mut socket = IcmpSocket::new(stack, &mut rx_meta, &mut rx_buffer, &mut tx_meta, &mut tx_buffer); + socket.bind(IcmpEndpoint::Ident(ident)).unwrap(); + + // Create the repr for the packet + let icmp_repr = Icmpv4Repr::EchoRequest { + ident, + seq_no: 0, + data: b"Hello, icmp!", + }; + + // Send the packet and store the starting instant to mesure latency later + let start = socket + .send_to_with(icmp_repr.buffer_len(), cfg.gateway.unwrap(), |buf| { + // Create and populate the packet buffer allocated by `send_to_with` + let mut icmp_packet = Icmpv4Packet::new_unchecked(buf); + icmp_repr.emit(&mut icmp_packet, &ChecksumCapabilities::default()); + Instant::now() // Return the instant where the packet was sent + }) + .await + .unwrap(); + + // Recieve and log the data of the reply + socket + .recv_from_with(|(buf, addr)| { + let packet = Icmpv4Packet::new_checked(buf).unwrap(); + info!( + "Recieved {:?} from {} in {}ms", + packet.data(), + addr, + start.elapsed().as_millis() + ); + }) + .await + .unwrap(); + + loop { + Timer::after_secs(10).await; + } +} + +async fn wait_for_config(stack: Stack<'static>) -> embassy_net::StaticConfigV4 { + loop { + if let Some(config) = stack.config_v4() { + return config.clone(); + } + yield_now().await; + } +} diff --git a/examples/rp235x/src/bin/ethernet_w5500_icmp_ping.rs b/examples/rp235x/src/bin/ethernet_w5500_icmp_ping.rs new file mode 100644 index 000000000..1f799a6b0 --- /dev/null +++ b/examples/rp235x/src/bin/ethernet_w5500_icmp_ping.rs @@ -0,0 +1,134 @@ +//! This example implements a LAN ping scan with the ping utilities in the icmp module of embassy-net. +//! +//! Example written for the [`WIZnet W5500-EVB-Pico2`](https://docs.wiznet.io/Product/iEthernet/W5500/w5500-evb-pico2) board. + +#![no_std] +#![no_main] + +use core::net::Ipv4Addr; +use core::ops::Not; +use core::str::FromStr; + +use defmt::*; +use embassy_executor::Spawner; +use embassy_futures::yield_now; +use embassy_net::icmp::ping::{PingManager, PingParams}; +use embassy_net::icmp::PacketMetadata; +use embassy_net::{Ipv4Cidr, Stack, StackResources}; +use embassy_net_wiznet::chip::W5500; +use embassy_net_wiznet::*; +use embassy_rp::clocks::RoscRng; +use embassy_rp::gpio::{Input, Level, Output, Pull}; +use embassy_rp::peripherals::SPI0; +use embassy_rp::spi::{Async, Config as SpiConfig, Spi}; +use embassy_time::{Delay, Duration}; +use embedded_hal_bus::spi::ExclusiveDevice; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +type ExclusiveSpiDevice = ExclusiveDevice, Output<'static>, Delay>; + +#[embassy_executor::task] +async fn ethernet_task(runner: Runner<'static, W5500, ExclusiveSpiDevice, Input<'static>, Output<'static>>) -> ! { + runner.run().await +} + +#[embassy_executor::task] +async fn net_task(mut runner: embassy_net::Runner<'static, Device<'static>>) -> ! { + runner.run().await +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let mut rng = RoscRng; + + let mut spi_cfg = SpiConfig::default(); + spi_cfg.frequency = 50_000_000; + let (miso, mosi, clk) = (p.PIN_16, p.PIN_19, p.PIN_18); + let spi = Spi::new(p.SPI0, clk, mosi, miso, p.DMA_CH0, p.DMA_CH1, spi_cfg); + let cs = Output::new(p.PIN_17, Level::High); + let w5500_int = Input::new(p.PIN_21, Pull::Up); + let w5500_reset = Output::new(p.PIN_20, Level::High); + + let mac_addr = [0x02, 0x00, 0x00, 0x00, 0x00, 0x00]; + static STATE: StaticCell> = StaticCell::new(); + let state = STATE.init(State::<8, 8>::new()); + let (device, runner) = embassy_net_wiznet::new( + mac_addr, + state, + ExclusiveDevice::new(spi, cs, Delay), + w5500_int, + w5500_reset, + ) + .await + .unwrap(); + unwrap!(spawner.spawn(ethernet_task(runner))); + + // Generate random seed + let seed = rng.next_u64(); + + // Init network stack + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new( + device, + embassy_net::Config::dhcpv4(Default::default()), + RESOURCES.init(StackResources::new()), + seed, + ); + + // Launch network task + unwrap!(spawner.spawn(net_task(runner))); + + info!("Waiting for DHCP..."); + let cfg = wait_for_config(stack).await; + let local_addr = cfg.address.address(); + info!("IP address: {:?}", local_addr); + let gateway = cfg.gateway.unwrap(); + let mask = cfg.address.netmask(); + let lower_bound = (gateway.to_bits() & mask.to_bits()) + 1; + let upper_bound = gateway.to_bits() | mask.to_bits().not(); + let addr_range = lower_bound..=upper_bound; + + // Then we can use it! + let mut rx_buffer = [0; 256]; + let mut tx_buffer = [0; 256]; + let mut rx_meta = [PacketMetadata::EMPTY]; + let mut tx_meta = [PacketMetadata::EMPTY]; + + // Create the ping manager instance + let mut ping_manager = PingManager::new(stack, &mut rx_meta, &mut rx_buffer, &mut tx_meta, &mut tx_buffer); + let addr = "192.168.8.1"; // Address to ping to + // Create the PingParams with the target address + let mut ping_params = PingParams::new(Ipv4Addr::from_str(addr).unwrap()); + // (optional) Set custom properties of the ping + ping_params.set_payload(b"Hello, Ping!"); // custom payload + ping_params.set_count(1); // ping 1 times per ping call + ping_params.set_timeout(Duration::from_millis(500)); // wait .5 seconds instead of 4 + + info!("Online hosts in {}:", Ipv4Cidr::from_netmask(gateway, mask).unwrap()); + let mut total_online_hosts = 0u32; + for addr in addr_range { + let ip_addr = Ipv4Addr::from_bits(addr); + // Set the target address in the ping params + ping_params.set_target(ip_addr); + // Execute the ping with the given parameters and wait for the reply + match ping_manager.ping(&ping_params).await { + Ok(time) => { + info!("{} is online\n- latency: {}ms\n", ip_addr, time.as_millis()); + total_online_hosts += 1; + } + _ => continue, + } + } + info!("Ping scan complete, total online hosts: {}", total_online_hosts); +} + +async fn wait_for_config(stack: Stack<'static>) -> embassy_net::StaticConfigV4 { + loop { + if let Some(config) = stack.config_v4() { + return config.clone(); + } + yield_now().await; + } +} diff --git a/examples/rp235x/src/bin/ethernet_w5500_multisocket.rs b/examples/rp235x/src/bin/ethernet_w5500_multisocket.rs new file mode 100644 index 000000000..fd8bc5c7a --- /dev/null +++ b/examples/rp235x/src/bin/ethernet_w5500_multisocket.rs @@ -0,0 +1,139 @@ +//! This example shows how you can allow multiple simultaneous TCP connections, by having multiple sockets listening on the same port. +//! +//! Example written for the [`WIZnet W5500-EVB-Pico2`](https://docs.wiznet.io/Product/iEthernet/W5500/w5500-evb-pico2) board. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_futures::yield_now; +use embassy_net::{Stack, StackResources}; +use embassy_net_wiznet::chip::W5500; +use embassy_net_wiznet::*; +use embassy_rp::clocks::RoscRng; +use embassy_rp::gpio::{Input, Level, Output, Pull}; +use embassy_rp::peripherals::SPI0; +use embassy_rp::spi::{Async, Config as SpiConfig, Spi}; +use embassy_time::{Delay, Duration}; +use embedded_hal_bus::spi::ExclusiveDevice; +use embedded_io_async::Write; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::task] +async fn ethernet_task( + runner: Runner< + 'static, + W5500, + ExclusiveDevice, Output<'static>, Delay>, + Input<'static>, + Output<'static>, + >, +) -> ! { + runner.run().await +} + +#[embassy_executor::task] +async fn net_task(mut runner: embassy_net::Runner<'static, Device<'static>>) -> ! { + runner.run().await +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let mut rng = RoscRng; + + let mut spi_cfg = SpiConfig::default(); + spi_cfg.frequency = 50_000_000; + let (miso, mosi, clk) = (p.PIN_16, p.PIN_19, p.PIN_18); + let spi = Spi::new(p.SPI0, clk, mosi, miso, p.DMA_CH0, p.DMA_CH1, spi_cfg); + let cs = Output::new(p.PIN_17, Level::High); + let w5500_int = Input::new(p.PIN_21, Pull::Up); + let w5500_reset = Output::new(p.PIN_20, Level::High); + + let mac_addr = [0x02, 0x00, 0x00, 0x00, 0x00, 0x00]; + static STATE: StaticCell> = StaticCell::new(); + let state = STATE.init(State::<8, 8>::new()); + let (device, runner) = embassy_net_wiznet::new( + mac_addr, + state, + ExclusiveDevice::new(spi, cs, Delay), + w5500_int, + w5500_reset, + ) + .await + .unwrap(); + unwrap!(spawner.spawn(ethernet_task(runner))); + + // Generate random seed + let seed = rng.next_u64(); + + // Init network stack + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new( + device, + embassy_net::Config::dhcpv4(Default::default()), + RESOURCES.init(StackResources::new()), + seed, + ); + + // Launch network task + unwrap!(spawner.spawn(net_task(runner))); + + info!("Waiting for DHCP..."); + let cfg = wait_for_config(stack).await; + let local_addr = cfg.address.address(); + info!("IP address: {:?}", local_addr); + + // Create two sockets listening to the same port, to handle simultaneous connections + unwrap!(spawner.spawn(listen_task(stack, 0, 1234))); + unwrap!(spawner.spawn(listen_task(stack, 1, 1234))); +} + +#[embassy_executor::task(pool_size = 2)] +async fn listen_task(stack: Stack<'static>, id: u8, port: u16) { + let mut rx_buffer = [0; 4096]; + let mut tx_buffer = [0; 4096]; + let mut buf = [0; 4096]; + loop { + let mut socket = embassy_net::tcp::TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer); + socket.set_timeout(Some(Duration::from_secs(10))); + + info!("SOCKET {}: Listening on TCP:{}...", id, port); + if let Err(e) = socket.accept(port).await { + warn!("accept error: {:?}", e); + continue; + } + info!("SOCKET {}: Received connection from {:?}", id, socket.remote_endpoint()); + + loop { + let n = match socket.read(&mut buf).await { + Ok(0) => { + warn!("read EOF"); + break; + } + Ok(n) => n, + Err(e) => { + warn!("SOCKET {}: {:?}", id, e); + break; + } + }; + info!("SOCKET {}: rxd {}", id, core::str::from_utf8(&buf[..n]).unwrap()); + + if let Err(e) = socket.write_all(&buf[..n]).await { + warn!("write error: {:?}", e); + break; + } + } + } +} + +async fn wait_for_config(stack: Stack<'static>) -> embassy_net::StaticConfigV4 { + loop { + if let Some(config) = stack.config_v4() { + return config.clone(); + } + yield_now().await; + } +} diff --git a/examples/rp235x/src/bin/ethernet_w5500_tcp_client.rs b/examples/rp235x/src/bin/ethernet_w5500_tcp_client.rs new file mode 100644 index 000000000..b726b9cc6 --- /dev/null +++ b/examples/rp235x/src/bin/ethernet_w5500_tcp_client.rs @@ -0,0 +1,127 @@ +//! This example implements a TCP client that attempts to connect to a host on port 1234 and send it some data once per second. +//! +//! Example written for the [`WIZnet W5500-EVB-Pico2`](https://docs.wiznet.io/Product/iEthernet/W5500/w5500-evb-pico2) board. + +#![no_std] +#![no_main] + +use core::str::FromStr; + +use defmt::*; +use embassy_executor::Spawner; +use embassy_futures::yield_now; +use embassy_net::{Stack, StackResources}; +use embassy_net_wiznet::chip::W5500; +use embassy_net_wiznet::*; +use embassy_rp::clocks::RoscRng; +use embassy_rp::gpio::{Input, Level, Output, Pull}; +use embassy_rp::peripherals::SPI0; +use embassy_rp::spi::{Async, Config as SpiConfig, Spi}; +use embassy_time::{Delay, Duration, Timer}; +use embedded_hal_bus::spi::ExclusiveDevice; +use embedded_io_async::Write; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::task] +async fn ethernet_task( + runner: Runner< + 'static, + W5500, + ExclusiveDevice, Output<'static>, Delay>, + Input<'static>, + Output<'static>, + >, +) -> ! { + runner.run().await +} + +#[embassy_executor::task] +async fn net_task(mut runner: embassy_net::Runner<'static, Device<'static>>) -> ! { + runner.run().await +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let mut rng = RoscRng; + let mut led = Output::new(p.PIN_25, Level::Low); + + let mut spi_cfg = SpiConfig::default(); + spi_cfg.frequency = 50_000_000; + let (miso, mosi, clk) = (p.PIN_16, p.PIN_19, p.PIN_18); + let spi = Spi::new(p.SPI0, clk, mosi, miso, p.DMA_CH0, p.DMA_CH1, spi_cfg); + let cs = Output::new(p.PIN_17, Level::High); + let w5500_int = Input::new(p.PIN_21, Pull::Up); + let w5500_reset = Output::new(p.PIN_20, Level::High); + + let mac_addr = [0x02, 0x00, 0x00, 0x00, 0x00, 0x00]; + static STATE: StaticCell> = StaticCell::new(); + let state = STATE.init(State::<8, 8>::new()); + let (device, runner) = embassy_net_wiznet::new( + mac_addr, + state, + ExclusiveDevice::new(spi, cs, Delay), + w5500_int, + w5500_reset, + ) + .await + .unwrap(); + unwrap!(spawner.spawn(ethernet_task(runner))); + + // Generate random seed + let seed = rng.next_u64(); + + // Init network stack + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new( + device, + embassy_net::Config::dhcpv4(Default::default()), + RESOURCES.init(StackResources::new()), + seed, + ); + + // Launch network task + unwrap!(spawner.spawn(net_task(runner))); + + info!("Waiting for DHCP..."); + let cfg = wait_for_config(stack).await; + let local_addr = cfg.address.address(); + info!("IP address: {:?}", local_addr); + + let mut rx_buffer = [0; 4096]; + let mut tx_buffer = [0; 4096]; + loop { + let mut socket = embassy_net::tcp::TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer); + socket.set_timeout(Some(Duration::from_secs(10))); + + led.set_low(); + info!("Connecting..."); + let host_addr = embassy_net::Ipv4Address::from_str("192.168.0.118").unwrap(); + if let Err(e) = socket.connect((host_addr, 1234)).await { + warn!("connect error: {:?}", e); + continue; + } + info!("Connected to {:?}", socket.remote_endpoint()); + led.set_high(); + + let msg = b"Hello world!\n"; + loop { + if let Err(e) = socket.write_all(msg).await { + warn!("write error: {:?}", e); + break; + } + info!("txd: {}", core::str::from_utf8(msg).unwrap()); + Timer::after_secs(1).await; + } + } +} + +async fn wait_for_config(stack: Stack<'static>) -> embassy_net::StaticConfigV4 { + loop { + if let Some(config) = stack.config_v4() { + return config.clone(); + } + yield_now().await; + } +} diff --git a/examples/rp235x/src/bin/ethernet_w5500_tcp_server.rs b/examples/rp235x/src/bin/ethernet_w5500_tcp_server.rs new file mode 100644 index 000000000..32b3880f6 --- /dev/null +++ b/examples/rp235x/src/bin/ethernet_w5500_tcp_server.rs @@ -0,0 +1,136 @@ +//! This example implements a TCP echo server on port 1234 and using DHCP. +//! Send it some data, you should see it echoed back and printed in the console. +//! +//! Example written for the [`WIZnet W5500-EVB-Pico2`](https://docs.wiznet.io/Product/iEthernet/W5500/w5500-evb-pico2) board. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_futures::yield_now; +use embassy_net::{Stack, StackResources}; +use embassy_net_wiznet::chip::W5500; +use embassy_net_wiznet::*; +use embassy_rp::clocks::RoscRng; +use embassy_rp::gpio::{Input, Level, Output, Pull}; +use embassy_rp::peripherals::SPI0; +use embassy_rp::spi::{Async, Config as SpiConfig, Spi}; +use embassy_time::{Delay, Duration}; +use embedded_hal_bus::spi::ExclusiveDevice; +use embedded_io_async::Write; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::task] +async fn ethernet_task( + runner: Runner< + 'static, + W5500, + ExclusiveDevice, Output<'static>, Delay>, + Input<'static>, + Output<'static>, + >, +) -> ! { + runner.run().await +} + +#[embassy_executor::task] +async fn net_task(mut runner: embassy_net::Runner<'static, Device<'static>>) -> ! { + runner.run().await +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let mut rng = RoscRng; + let mut led = Output::new(p.PIN_25, Level::Low); + + let mut spi_cfg = SpiConfig::default(); + spi_cfg.frequency = 50_000_000; + let (miso, mosi, clk) = (p.PIN_16, p.PIN_19, p.PIN_18); + let spi = Spi::new(p.SPI0, clk, mosi, miso, p.DMA_CH0, p.DMA_CH1, spi_cfg); + let cs = Output::new(p.PIN_17, Level::High); + let w5500_int = Input::new(p.PIN_21, Pull::Up); + let w5500_reset = Output::new(p.PIN_20, Level::High); + + let mac_addr = [0x02, 0x00, 0x00, 0x00, 0x00, 0x00]; + static STATE: StaticCell> = StaticCell::new(); + let state = STATE.init(State::<8, 8>::new()); + let (device, runner) = embassy_net_wiznet::new( + mac_addr, + state, + ExclusiveDevice::new(spi, cs, Delay), + w5500_int, + w5500_reset, + ) + .await + .unwrap(); + unwrap!(spawner.spawn(ethernet_task(runner))); + + // Generate random seed + let seed = rng.next_u64(); + + // Init network stack + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new( + device, + embassy_net::Config::dhcpv4(Default::default()), + RESOURCES.init(StackResources::new()), + seed, + ); + + // Launch network task + unwrap!(spawner.spawn(net_task(runner))); + + info!("Waiting for DHCP..."); + let cfg = wait_for_config(stack).await; + let local_addr = cfg.address.address(); + info!("IP address: {:?}", local_addr); + + let mut rx_buffer = [0; 4096]; + let mut tx_buffer = [0; 4096]; + let mut buf = [0; 4096]; + loop { + let mut socket = embassy_net::tcp::TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer); + socket.set_timeout(Some(Duration::from_secs(10))); + + led.set_low(); + info!("Listening on TCP:1234..."); + if let Err(e) = socket.accept(1234).await { + warn!("accept error: {:?}", e); + continue; + } + info!("Received connection from {:?}", socket.remote_endpoint()); + led.set_high(); + + loop { + let n = match socket.read(&mut buf).await { + Ok(0) => { + warn!("read EOF"); + break; + } + Ok(n) => n, + Err(e) => { + warn!("{:?}", e); + break; + } + }; + info!("rxd {}", core::str::from_utf8(&buf[..n]).unwrap()); + + if let Err(e) = socket.write_all(&buf[..n]).await { + warn!("write error: {:?}", e); + break; + } + } + } +} + +async fn wait_for_config(stack: Stack<'static>) -> embassy_net::StaticConfigV4 { + loop { + if let Some(config) = stack.config_v4() { + return config.clone(); + } + yield_now().await; + } +} diff --git a/examples/rp235x/src/bin/ethernet_w5500_udp.rs b/examples/rp235x/src/bin/ethernet_w5500_udp.rs new file mode 100644 index 000000000..cd0824df1 --- /dev/null +++ b/examples/rp235x/src/bin/ethernet_w5500_udp.rs @@ -0,0 +1,116 @@ +//! This example implements a UDP server listening on port 1234 and echoing back the data. +//! +//! Example written for the [`WIZnet W5500-EVB-Pico2`](https://docs.wiznet.io/Product/iEthernet/W5500/w5500-evb-pico2) board. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_futures::yield_now; +use embassy_net::udp::{PacketMetadata, UdpSocket}; +use embassy_net::{Stack, StackResources}; +use embassy_net_wiznet::chip::W5500; +use embassy_net_wiznet::*; +use embassy_rp::clocks::RoscRng; +use embassy_rp::gpio::{Input, Level, Output, Pull}; +use embassy_rp::peripherals::SPI0; +use embassy_rp::spi::{Async, Config as SpiConfig, Spi}; +use embassy_time::Delay; +use embedded_hal_bus::spi::ExclusiveDevice; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::task] +async fn ethernet_task( + runner: Runner< + 'static, + W5500, + ExclusiveDevice, Output<'static>, Delay>, + Input<'static>, + Output<'static>, + >, +) -> ! { + runner.run().await +} + +#[embassy_executor::task] +async fn net_task(mut runner: embassy_net::Runner<'static, Device<'static>>) -> ! { + runner.run().await +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let mut rng = RoscRng; + + let mut spi_cfg = SpiConfig::default(); + spi_cfg.frequency = 50_000_000; + let (miso, mosi, clk) = (p.PIN_16, p.PIN_19, p.PIN_18); + let spi = Spi::new(p.SPI0, clk, mosi, miso, p.DMA_CH0, p.DMA_CH1, spi_cfg); + let cs = Output::new(p.PIN_17, Level::High); + let w5500_int = Input::new(p.PIN_21, Pull::Up); + let w5500_reset = Output::new(p.PIN_20, Level::High); + + let mac_addr = [0x02, 0x00, 0x00, 0x00, 0x00, 0x00]; + static STATE: StaticCell> = StaticCell::new(); + let state = STATE.init(State::<8, 8>::new()); + let (device, runner) = embassy_net_wiznet::new( + mac_addr, + state, + ExclusiveDevice::new(spi, cs, Delay), + w5500_int, + w5500_reset, + ) + .await + .unwrap(); + unwrap!(spawner.spawn(ethernet_task(runner))); + + // Generate random seed + let seed = rng.next_u64(); + + // Init network stack + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new( + device, + embassy_net::Config::dhcpv4(Default::default()), + RESOURCES.init(StackResources::new()), + seed, + ); + + // Launch network task + unwrap!(spawner.spawn(net_task(runner))); + + info!("Waiting for DHCP..."); + let cfg = wait_for_config(stack).await; + let local_addr = cfg.address.address(); + info!("IP address: {:?}", local_addr); + + // Then we can use it! + let mut rx_buffer = [0; 4096]; + let mut tx_buffer = [0; 4096]; + let mut rx_meta = [PacketMetadata::EMPTY; 16]; + let mut tx_meta = [PacketMetadata::EMPTY; 16]; + let mut buf = [0; 4096]; + loop { + let mut socket = UdpSocket::new(stack, &mut rx_meta, &mut rx_buffer, &mut tx_meta, &mut tx_buffer); + socket.bind(1234).unwrap(); + + loop { + let (n, ep) = socket.recv_from(&mut buf).await.unwrap(); + if let Ok(s) = core::str::from_utf8(&buf[..n]) { + info!("rxd from {}: {}", ep, s); + } + socket.send_to(&buf[..n], ep).await.unwrap(); + } + } +} + +async fn wait_for_config(stack: Stack<'static>) -> embassy_net::StaticConfigV4 { + loop { + if let Some(config) = stack.config_v4() { + return config.clone(); + } + yield_now().await; + } +} From a165339276e751909a88f685760f4cabb71e50d1 Mon Sep 17 00:00:00 2001 From: nerwalt Date: Thu, 7 Aug 2025 09:07:29 -0600 Subject: [PATCH 2/2] Adds RRAMC support for the nrf54l15 Adds an Nvmc driver alias for compatibility --- embassy-nrf/src/chips/nrf54l15_app.rs | 8 +- embassy-nrf/src/lib.rs | 6 +- embassy-nrf/src/rramc.rs | 176 ++++++++++++++++++++++++++ examples/nrf54l15/Cargo.toml | 2 + examples/nrf54l15/src/bin/nvmc.rs | 44 +++++++ 5 files changed, 234 insertions(+), 2 deletions(-) create mode 100644 embassy-nrf/src/rramc.rs create mode 100644 examples/nrf54l15/src/bin/nvmc.rs diff --git a/embassy-nrf/src/chips/nrf54l15_app.rs b/embassy-nrf/src/chips/nrf54l15_app.rs index b133eb565..3a4e1ae4a 100644 --- a/embassy-nrf/src/chips/nrf54l15_app.rs +++ b/embassy-nrf/src/chips/nrf54l15_app.rs @@ -201,9 +201,15 @@ pub mod pac { pub const EASY_DMA_SIZE: usize = (1 << 16) - 1; //pub const FORCE_COPY_BUFFER_SIZE: usize = 1024; -//pub const FLASH_SIZE: usize = 1024 * 1024; +// 1.5 MB NVM +#[allow(unused)] +pub const FLASH_SIZE: usize = 1536 * 1024; embassy_hal_internal::peripherals! { + #[cfg(feature = "_s")] + // RRAMC + RRAMC, + // GPIO port 0 P0_00, P0_01, diff --git a/embassy-nrf/src/lib.rs b/embassy-nrf/src/lib.rs index ba8206d13..d3c4b3bb1 100644 --- a/embassy-nrf/src/lib.rs +++ b/embassy-nrf/src/lib.rs @@ -98,8 +98,12 @@ pub mod ipc; feature = "_nrf5340-app" ))] pub mod nfct; -#[cfg(not(feature = "_nrf54l"))] // TODO +#[cfg(not(feature = "_nrf54l"))] pub mod nvmc; +#[cfg(feature = "nrf54l15-app-s")] +pub mod rramc; +#[cfg(feature = "nrf54l15-app-s")] +pub use rramc as nvmc; #[cfg(not(feature = "_nrf54l"))] // TODO #[cfg(any( feature = "nrf52810", diff --git a/embassy-nrf/src/rramc.rs b/embassy-nrf/src/rramc.rs new file mode 100644 index 000000000..7cb5660cb --- /dev/null +++ b/embassy-nrf/src/rramc.rs @@ -0,0 +1,176 @@ +//! Resistive Random-Access Memory Controller driver. + +use core::{ptr, slice}; + +use embedded_storage::nor_flash::{ + ErrorType, MultiwriteNorFlash, NorFlash, NorFlashError, NorFlashErrorKind, ReadNorFlash, +}; + +use crate::peripherals::RRAMC; +use crate::{pac, Peri}; + +// +// Export Nvmc alias and page size for downstream compatibility +// +/// RRAM-backed `Nvmc` compatibile driver. +pub type Nvmc<'d> = Rramc<'d>; +/// Emulated page size. RRAM does not use pages. This exists only for downstream compatibility. +pub const PAGE_SIZE: usize = 4096; + +// In bytes, one line is 128 bits +const WRITE_LINE_SIZE: usize = 16; + +/// Size of RRAM flash in bytes. +pub const FLASH_SIZE: usize = crate::chip::FLASH_SIZE; + +/// Error type for RRAMC operations. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Error { + /// Operation using a location not in flash. + OutOfBounds, + /// Unaligned operation or using unaligned buffers. + Unaligned, +} + +impl NorFlashError for Error { + fn kind(&self) -> NorFlashErrorKind { + match self { + Self::OutOfBounds => NorFlashErrorKind::OutOfBounds, + Self::Unaligned => NorFlashErrorKind::NotAligned, + } + } +} + +/// Resistive Random-Access Memory Controller (RRAMC) that implements the `embedded-storage` +/// traits. +pub struct Rramc<'d> { + _p: Peri<'d, RRAMC>, +} + +impl<'d> Rramc<'d> { + /// Create Rramc driver. + pub fn new(_p: Peri<'d, RRAMC>) -> Self { + Self { _p } + } + + fn regs() -> pac::rramc::Rramc { + pac::RRAMC + } + + fn wait_ready(&mut self) { + let p = Self::regs(); + while !p.ready().read().ready() {} + } + + fn wait_ready_write(&mut self) { + let p = Self::regs(); + while !p.readynext().read().readynext() {} + while !p.bufstatus().writebufempty().read().empty() {} + } + + fn enable_read(&self) { + Self::regs().config().write(|w| w.set_wen(false)); + } + + fn enable_write(&self) { + Self::regs().config().write(|w| w.set_wen(true)); + } +} + +// +// RRAM is not NOR flash, but many crates require embedded-storage NorFlash traits. We therefore +// implement the traits for downstream compatibility. +// + +impl<'d> MultiwriteNorFlash for Rramc<'d> {} + +impl<'d> ErrorType for Rramc<'d> { + type Error = Error; +} + +impl<'d> ReadNorFlash for Rramc<'d> { + const READ_SIZE: usize = 1; + + fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> { + if offset as usize >= FLASH_SIZE || offset as usize + bytes.len() > FLASH_SIZE { + return Err(Error::OutOfBounds); + } + + let flash_data = unsafe { slice::from_raw_parts(offset as *const u8, bytes.len()) }; + bytes.copy_from_slice(flash_data); + Ok(()) + } + + fn capacity(&self) -> usize { + FLASH_SIZE + } +} + +impl<'d> NorFlash for Rramc<'d> { + const WRITE_SIZE: usize = WRITE_LINE_SIZE; + const ERASE_SIZE: usize = PAGE_SIZE; + + // RRAM can overwrite in-place, so emulate page erases by overwriting the page bytes with 0xFF. + fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> { + if to < from || to as usize > FLASH_SIZE { + return Err(Error::OutOfBounds); + } + if from as usize % Self::ERASE_SIZE != 0 || to as usize % Self::ERASE_SIZE != 0 { + return Err(Error::Unaligned); + } + + self.enable_write(); + self.wait_ready(); + + // Treat each emulated page separately so callers can rely on post‑erase read‑back + // returning 0xFF just like on real NOR flash. + let buf = [0xFFu8; Self::WRITE_SIZE]; + for page_addr in (from..to).step_by(Self::ERASE_SIZE) { + let page_end = page_addr + Self::ERASE_SIZE as u32; + for line_addr in (page_addr..page_end).step_by(Self::WRITE_SIZE) { + unsafe { + let src = buf.as_ptr() as *const u32; + let dst = line_addr as *mut u32; + for i in 0..(Self::WRITE_SIZE / 4) { + core::ptr::write_volatile(dst.add(i), core::ptr::read_unaligned(src.add(i))); + } + } + self.wait_ready_write(); + } + } + + self.enable_read(); + self.wait_ready(); + Ok(()) + } + + fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> { + if offset as usize + bytes.len() > FLASH_SIZE { + return Err(Error::OutOfBounds); + } + if offset as usize % Self::WRITE_SIZE != 0 || bytes.len() % Self::WRITE_SIZE != 0 { + return Err(Error::Unaligned); + } + + self.enable_write(); + self.wait_ready(); + + unsafe { + let p_src = bytes.as_ptr() as *const u32; + let p_dst = offset as *mut u32; + let words = bytes.len() / 4; + for i in 0..words { + let w = ptr::read_unaligned(p_src.add(i)); + ptr::write_volatile(p_dst.add(i), w); + if (i + 1) % (Self::WRITE_SIZE / 4) == 0 { + self.wait_ready_write(); + } + } + } + + self.enable_read(); + self.wait_ready(); + Ok(()) + } +} diff --git a/examples/nrf54l15/Cargo.toml b/examples/nrf54l15/Cargo.toml index faa3a4abe..5f1ee50a0 100644 --- a/examples/nrf54l15/Cargo.toml +++ b/examples/nrf54l15/Cargo.toml @@ -16,5 +16,7 @@ panic-probe = { version = "1.0.0", features = ["print-defmt"] } cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } cortex-m-rt = "0.7.0" +embedded-storage = "0.3.1" + [profile.release] debug = 2 diff --git a/examples/nrf54l15/src/bin/nvmc.rs b/examples/nrf54l15/src/bin/nvmc.rs new file mode 100644 index 000000000..f990604cd --- /dev/null +++ b/examples/nrf54l15/src/bin/nvmc.rs @@ -0,0 +1,44 @@ +#![no_std] +#![no_main] + +use defmt::{info, unwrap}; +use embassy_executor::Spawner; +use embassy_nrf::nvmc::{Nvmc, PAGE_SIZE}; +use embedded_storage::nor_flash::{NorFlash, ReadNorFlash}; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_nrf::init(Default::default()); + info!("Hello RRAMC NVMC!"); + + let mut f = Nvmc::new(p.RRAMC); + + const ADDR: u32 = 0x80000; + let mut buf = [0u8; 4]; + + info!("Reading..."); + unwrap!(f.read(ADDR, &mut buf)); + info!("Read: {=[u8]:x}", buf); + + info!("Erasing..."); + unwrap!(f.erase(ADDR, ADDR + PAGE_SIZE as u32)); + + info!("Reading..."); + unwrap!(f.read(ADDR, &mut buf)); + info!("Read: {=[u8]:x}", buf); + + info!("Writing..."); + // 16 B (128-bit) write minimum + let out: [u8; 16] = [ + 0xaa, 0xaa, 0xaa, 0xaa, 0xbb, 0xbb, 0xbb, 0xbb, 0xcc, 0xcc, 0xcc, 0xcc, 0xdd, 0xdd, 0xdd, 0xdd, + ]; + unwrap!(f.write(ADDR, &out)); + + info!("Reading..."); + // Can read arbitrary sizes + for addr in (ADDR..ADDR + 16).step_by(4) { + unwrap!(f.read(addr, &mut buf)); + info!("Read: {=[u8]:x}", buf); + } +}