This commit is contained in:
kalkyl
2023-05-09 01:51:08 +02:00
commit 72b0379125
20 changed files with 1389 additions and 0 deletions

View File

@ -0,0 +1,8 @@
[target.'cfg(all(target_arch = "arm", target_os = "none"))']
runner = "probe-rs-cli run --chip RP2040"
[build]
target = "thumbv6m-none-eabi"
[env]
DEFMT_LOG = "info"

70
examples/Cargo.toml Normal file
View File

@ -0,0 +1,70 @@
[package]
name = "embassy-net-w5500-examples"
version = "0.1.0"
edition = "2021"
[dependencies]
embassy-executor = { version = "0.1.0", features = ["defmt", "integrated-timers", "executor-thread", "arch-cortex-m"] }
embassy-time = { version = "0.1.0", features = ["defmt", "defmt-timestamp-uptime"] }
embassy-rp = { version = "0.1.0", features = ["defmt", "unstable-traits", "nightly", "unstable-pac", "time-driver"] }
embassy-net = { version = "0.1.0", features = ["defmt", "tcp", "udp", "dhcpv4", "medium-ethernet", "unstable-traits", "nightly"] }
embassy-sync = { version = "0.1.0" }
embassy-futures = { version = "0.1.0" }
embassy-net-driver = { version = "0.1.0" }
embassy-net-driver-channel = { version = "0.1.0" }
atomic-polyfill = "0.1.5"
static_cell = "1.0"
defmt = "=0.3.2"
defmt-rtt = "0.3"
panic-probe = { version = "0.3", features = ["print-defmt"] }
cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] }
cortex-m-rt = "0.7.0"
embedded-io = { version = "0.4.0", features = ["async", "defmt"] }
heapless = "0.7.15"
embedded-hal = { version = "1.0.0-alpha.10" }
embedded-hal-async = { version = "=0.2.0-alpha.1" }
rand = { version = "0.8.5", default-features = false }
embassy-net-w5500 = { path = "../" }
[patch.crates-io]
embassy-executor = { git = "https://github.com/embassy-rs/embassy", rev = "03d6363d5af5dcaf21b52734994a466ca593d2b6" }
embassy-time = { git = "https://github.com/embassy-rs/embassy", rev = "03d6363d5af5dcaf21b52734994a466ca593d2b6" }
embassy-futures = { git = "https://github.com/embassy-rs/embassy", rev = "03d6363d5af5dcaf21b52734994a466ca593d2b6" }
embassy-sync = { git = "https://github.com/embassy-rs/embassy", rev = "03d6363d5af5dcaf21b52734994a466ca593d2b6" }
embassy-rp = { git = "https://github.com/embassy-rs/embassy", rev = "03d6363d5af5dcaf21b52734994a466ca593d2b6" }
embassy-net = { git = "https://github.com/embassy-rs/embassy", rev = "03d6363d5af5dcaf21b52734994a466ca593d2b6" }
embassy-net-driver = { git = "https://github.com/embassy-rs/embassy", rev = "03d6363d5af5dcaf21b52734994a466ca593d2b6" }
embassy-net-driver-channel = { git = "https://github.com/embassy-rs/embassy", rev = "03d6363d5af5dcaf21b52734994a466ca593d2b6" }
[profile.dev]
debug = 2
debug-assertions = true
opt-level = 1
overflow-checks = true
[profile.release]
codegen-units = 1
debug = 1
debug-assertions = false
incremental = false
lto = 'fat'
opt-level = 'z'
overflow-checks = false
# do not optimize proc-macro crates = faster builds from scratch
[profile.dev.build-override]
codegen-units = 8
debug = false
debug-assertions = false
opt-level = 0
overflow-checks = false
[profile.release.build-override]
codegen-units = 8
debug = false
debug-assertions = false
opt-level = 0
overflow-checks = false

33
examples/README.md Normal file
View File

@ -0,0 +1,33 @@
# Examples for the rp2040 `WIZnet W5500-EVB-Pico` board
Examples are written for the [`WIZnet W5500-EVB-Pico`](https://www.wiznet.io/product-item/w5500-evb-pico/) board.
## Prerequisites
```bash
cargo install probe-rs-cli
```
## TCP server example
```bash
cargo run --bin tcp-server --release
```
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.
## Multi-socket example
```bash
cargo run --bin multisocket --release
```
This example shows how you can allow multiple simultaneous TCP connections, by having multiple sockets listening on the same port.
## TCP client example
```bash
cargo run --bin tcp-client --release
```
This example implements a TCP client that attempts to connect to a host on port 1234 and send it some data once per second.
## UDP server example
```bash
cargo run --bin udp --release
```
This example implements a UDP server listening on port 1234 and echoing back the data.

36
examples/build.rs Normal file
View File

@ -0,0 +1,36 @@
//! This build script copies the `memory.x` file from the crate root into
//! a directory where the linker can always find it at build time.
//! For many projects this is optional, as the linker always searches the
//! project root directory -- wherever `Cargo.toml` is. However, if you
//! are using a workspace or have a more complicated build setup, this
//! build script becomes required. Additionally, by requesting that
//! Cargo re-run the build script whenever `memory.x` is changed,
//! updating `memory.x` ensures a rebuild of the application with the
//! new memory settings.
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
fn main() {
// Put `memory.x` in our output directory and ensure it's
// on the linker search path.
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
File::create(out.join("memory.x"))
.unwrap()
.write_all(include_bytes!("memory.x"))
.unwrap();
println!("cargo:rustc-link-search={}", out.display());
// By default, Cargo will re-run a build script whenever
// any file in the project changes. By specifying `memory.x`
// here, we ensure the build script is only re-run when
// `memory.x` is changed.
println!("cargo:rerun-if-changed=memory.x");
println!("cargo:rustc-link-arg-bins=--nmagic");
println!("cargo:rustc-link-arg-bins=-Tlink.x");
println!("cargo:rustc-link-arg-bins=-Tlink-rp.x");
println!("cargo:rustc-link-arg-bins=-Tdefmt.x");
}

5
examples/memory.x Normal file
View File

@ -0,0 +1,5 @@
MEMORY {
BOOT2 : ORIGIN = 0x10000000, LENGTH = 0x100
FLASH : ORIGIN = 0x10000100, LENGTH = 1024K - 0x100
RAM : ORIGIN = 0x20000000, LENGTH = 256K
}

View File

@ -0,0 +1,148 @@
#![no_std]
#![no_main]
#![feature(type_alias_impl_trait)]
use defmt::*;
use embassy_executor::Spawner;
use embassy_futures::yield_now;
use embassy_net::{Stack, StackResources};
use embassy_net_w5500::*;
use embassy_rp::clocks::RoscRng;
use embassy_rp::gpio::{Input, Level, Output, Pull};
use embassy_rp::peripherals::{PIN_17, PIN_20, PIN_21, SPI0};
use embassy_rp::spi::{Async, Config as SpiConfig, Spi};
use embedded_hal_async::spi::ExclusiveDevice;
use embedded_io::asynch::Write;
use rand::RngCore;
use static_cell::StaticCell;
use {defmt_rtt as _, panic_probe as _};
macro_rules! singleton {
($val:expr) => {{
type T = impl Sized;
static STATIC_CELL: StaticCell<T> = StaticCell::new();
let (x,) = STATIC_CELL.init(($val,));
x
}};
}
#[embassy_executor::task]
async fn ethernet_task(
runner: Runner<
'static,
ExclusiveDevice<Spi<'static, SPI0, Async>, Output<'static, PIN_17>>,
Input<'static, PIN_21>,
Output<'static, PIN_20>,
>,
) -> ! {
runner.run().await
}
#[embassy_executor::task]
async fn net_task(stack: &'static Stack<Device<'static>>) -> ! {
stack.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];
let state = singleton!(State::<8, 8>::new());
let (device, runner) = embassy_net_w5500::new(
mac_addr,
state,
ExclusiveDevice::new(spi, cs),
w5500_int,
w5500_reset,
)
.await;
unwrap!(spawner.spawn(ethernet_task(runner)));
// Generate random seed
let seed = rng.next_u64();
// Init network stack
let stack = &*singleton!(Stack::new(
device,
embassy_net::Config::Dhcp(Default::default()),
singleton!(StackResources::<3>::new()),
seed
));
// Launch network task
unwrap!(spawner.spawn(net_task(&stack)));
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: &'static Stack<Device<'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(embassy_net::SmolDuration::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: &'static Stack<Device<'static>>) -> embassy_net::StaticConfig {
loop {
if let Some(config) = stack.config() {
return config.clone();
}
yield_now().await;
}
}

View File

@ -0,0 +1,128 @@
#![no_std]
#![no_main]
#![feature(type_alias_impl_trait)]
use core::str::FromStr;
use defmt::*;
use embassy_executor::Spawner;
use embassy_futures::yield_now;
use embassy_net::{Stack, StackResources};
use embassy_net_w5500::*;
use embassy_rp::clocks::RoscRng;
use embassy_rp::gpio::{Input, Level, Output, Pull};
use embassy_rp::peripherals::{PIN_17, PIN_20, PIN_21, SPI0};
use embassy_rp::spi::{Async, Config as SpiConfig, Spi};
use embassy_time::{Duration, Timer};
use embedded_hal_async::spi::ExclusiveDevice;
use embedded_io::asynch::Write;
use rand::RngCore;
use static_cell::StaticCell;
use {defmt_rtt as _, panic_probe as _};
macro_rules! singleton {
($val:expr) => {{
type T = impl Sized;
static STATIC_CELL: StaticCell<T> = StaticCell::new();
let (x,) = STATIC_CELL.init(($val,));
x
}};
}
#[embassy_executor::task]
async fn ethernet_task(
runner: Runner<
'static,
ExclusiveDevice<Spi<'static, SPI0, Async>, Output<'static, PIN_17>>,
Input<'static, PIN_21>,
Output<'static, PIN_20>,
>,
) -> ! {
runner.run().await
}
#[embassy_executor::task]
async fn net_task(stack: &'static Stack<Device<'static>>) -> ! {
stack.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];
let state = singleton!(State::<8, 8>::new());
let (device, runner) = embassy_net_w5500::new(
mac_addr,
state,
ExclusiveDevice::new(spi, cs),
w5500_int,
w5500_reset,
)
.await;
unwrap!(spawner.spawn(ethernet_task(runner)));
// Generate random seed
let seed = rng.next_u64();
// Init network stack
let stack = &*singleton!(Stack::new(
device,
embassy_net::Config::Dhcp(Default::default()),
singleton!(StackResources::<2>::new()),
seed
));
// Launch network task
unwrap!(spawner.spawn(net_task(&stack)));
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(embassy_net::SmolDuration::from_secs(10)));
led.set_low();
info!("Connecting...");
let host_addr = embassy_net::Ipv4Address::from_str("192.168.1.110").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(Duration::from_secs(1)).await;
}
}
}
async fn wait_for_config(stack: &'static Stack<Device<'static>>) -> embassy_net::StaticConfig {
loop {
if let Some(config) = stack.config() {
return config.clone();
}
yield_now().await;
}
}

View File

@ -0,0 +1,136 @@
#![no_std]
#![no_main]
#![feature(type_alias_impl_trait)]
use defmt::*;
use embassy_executor::Spawner;
use embassy_futures::yield_now;
use embassy_net::{Stack, StackResources};
use embassy_net_w5500::*;
use embassy_rp::clocks::RoscRng;
use embassy_rp::gpio::{Input, Level, Output, Pull};
use embassy_rp::peripherals::{PIN_17, PIN_20, PIN_21, SPI0};
use embassy_rp::spi::{Async, Config as SpiConfig, Spi};
use embedded_hal_async::spi::ExclusiveDevice;
use embedded_io::asynch::Write;
use rand::RngCore;
use static_cell::StaticCell;
use {defmt_rtt as _, panic_probe as _};
macro_rules! singleton {
($val:expr) => {{
type T = impl Sized;
static STATIC_CELL: StaticCell<T> = StaticCell::new();
let (x,) = STATIC_CELL.init(($val,));
x
}};
}
#[embassy_executor::task]
async fn ethernet_task(
runner: Runner<
'static,
ExclusiveDevice<Spi<'static, SPI0, Async>, Output<'static, PIN_17>>,
Input<'static, PIN_21>,
Output<'static, PIN_20>,
>,
) -> ! {
runner.run().await
}
#[embassy_executor::task]
async fn net_task(stack: &'static Stack<Device<'static>>) -> ! {
stack.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];
let state = singleton!(State::<8, 8>::new());
let (device, runner) = embassy_net_w5500::new(
mac_addr,
state,
ExclusiveDevice::new(spi, cs),
w5500_int,
w5500_reset,
)
.await;
unwrap!(spawner.spawn(ethernet_task(runner)));
// Generate random seed
let seed = rng.next_u64();
// Init network stack
let stack = &*singleton!(Stack::new(
device,
embassy_net::Config::Dhcp(Default::default()),
singleton!(StackResources::<2>::new()),
seed
));
// Launch network task
unwrap!(spawner.spawn(net_task(&stack)));
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(embassy_net::SmolDuration::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: &'static Stack<Device<'static>>) -> embassy_net::StaticConfig {
loop {
if let Some(config) = stack.config() {
return config.clone();
}
yield_now().await;
}
}

123
examples/src/bin/udp.rs Normal file
View File

@ -0,0 +1,123 @@
#![no_std]
#![no_main]
#![feature(type_alias_impl_trait)]
use defmt::*;
use embassy_executor::Spawner;
use embassy_futures::yield_now;
use embassy_net::udp::UdpSocket;
use embassy_net::{PacketMetadata, Stack, StackResources};
use embassy_net_w5500::*;
use embassy_rp::clocks::RoscRng;
use embassy_rp::gpio::{Input, Level, Output, Pull};
use embassy_rp::peripherals::{PIN_17, PIN_20, PIN_21, SPI0};
use embassy_rp::spi::{Async, Config as SpiConfig, Spi};
use embedded_hal_async::spi::ExclusiveDevice;
use rand::RngCore;
use static_cell::StaticCell;
use {defmt_rtt as _, panic_probe as _};
macro_rules! singleton {
($val:expr) => {{
type T = impl Sized;
static STATIC_CELL: StaticCell<T> = StaticCell::new();
let (x,) = STATIC_CELL.init(($val,));
x
}};
}
#[embassy_executor::task]
async fn ethernet_task(
runner: Runner<
'static,
ExclusiveDevice<Spi<'static, SPI0, Async>, Output<'static, PIN_17>>,
Input<'static, PIN_21>,
Output<'static, PIN_20>,
>,
) -> ! {
runner.run().await
}
#[embassy_executor::task]
async fn net_task(stack: &'static Stack<Device<'static>>) -> ! {
stack.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];
let state = singleton!(State::<8, 8>::new());
let (device, runner) = embassy_net_w5500::new(
mac_addr,
state,
ExclusiveDevice::new(spi, cs),
w5500_int,
w5500_reset,
)
.await;
unwrap!(spawner.spawn(ethernet_task(runner)));
// Generate random seed
let seed = rng.next_u64();
// Init network stack
let stack = &*singleton!(Stack::new(
device,
embassy_net::Config::Dhcp(Default::default()),
singleton!(StackResources::<2>::new()),
seed
));
// Launch network task
unwrap!(spawner.spawn(net_task(&stack)));
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: &'static Stack<Device<'static>>) -> embassy_net::StaticConfig {
loop {
if let Some(config) = stack.config() {
return config.clone();
}
yield_now().await;
}
}