Initial commit, logs all ADC when pinged by TCP

This commit is contained in:
JP Stringham
2026-02-04 09:22:40 -05:00
commit f9d62207b3
8 changed files with 2349 additions and 0 deletions

15
.cargo/config.toml Normal file
View File

@@ -0,0 +1,15 @@
[build]
target = "thumbv6m-none-eabi"
# Target specific options
[target.thumbv6m-none-eabi]
# This runner will make a UF2 file and then copy it to a mounted RP2040 in USB
# Bootloader mode:
runner = "elf2uf2-rs -d"
# runner = "probe-rs run --chip RP2040"
[env]
DEFMT_RTT_BUFFER_SIZE = { value = "4096", force = true }
DEFMT_LOG = { value = "info", force = true }

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/target

6
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,6 @@
{
"rust-analyzer.cargo.target": "thumbv6m-none-eabi",
"rust-analyzer.check.allTargets": false,
"editor.defaultFormatter": "rust-lang.rust-analyzer",
"editor.formatOnSave": true,
}

2029
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

52
Cargo.toml Normal file
View File

@@ -0,0 +1,52 @@
[package]
name = "pico-w-remote-temp-logger"
version = "0.1.0"
edition = "2024"
[dependencies]
embassy-embedded-hal = { version = "0.5.0", path = "../embassy/embassy-embedded-hal", features = ["defmt"] }
embassy-sync = { version = "0.7.2", path = "../embassy/embassy-sync", features = ["defmt"] }
embassy-executor = { version = "0.9.0", path = "../embassy/embassy-executor", features = ["arch-cortex-m", "executor-thread", "executor-interrupt", "defmt"] }
embassy-time = { version = "0.5.0", path = "../embassy/embassy-time", features = ["defmt", "defmt-timestamp-uptime"] }
embassy-rp = { version = "0.9.0", path = "../embassy/embassy-rp", features = ["defmt", "unstable-pac", "time-driver", "critical-section-impl", "rp2040"] }
embassy-usb = { version = "0.5.1", path = "../embassy/embassy-usb", features = ["defmt"] }
embassy-net = { version = "0.8.0", path = "../embassy/embassy-net", features = ["defmt", "icmp", "tcp", "udp", "raw", "dhcpv4", "medium-ethernet", "dns", "proto-ipv4", "proto-ipv6", "multicast"] }
embassy-net-wiznet = { version = "0.2.1", path = "../embassy/embassy-net-wiznet", features = ["defmt"] }
embassy-futures = { version = "0.1.2", path = "../embassy/embassy-futures" }
embassy-usb-logger = { version = "0.5.1", path = "../embassy/embassy-usb-logger" }
cyw43 = { version = "0.6.0", path = "../embassy/cyw43", features = ["defmt", "firmware-logs"] }
cyw43-pio = { version = "0.9.0", path = "../embassy/cyw43-pio", features = ["defmt"] }
defmt = "1.0"
defmt-rtt = "1.1"
fixed = "1.29.0"
fixed-macro = "1.2"
cortex-m = { version = "0.7.7", features = ["inline-asm"] }
cortex-m-rt = "0.7.5"
panic-probe = { version = "1.0", features = ["print-defmt"] }
futures = { version = "0.3.31", default-features = false, features = ["async-await", "cfg-target-has-atomic", "unstable"] }
heapless = "0.9"
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0" }
embedded-hal-async = "1.0.0"
embedded-hal-bus = { version = "0.3.0", features = ["async"] }
embedded-io-async = { version = "0.7.0", features = ["defmt"] }
#embedded-storage = { version = "0.3" }
static_cell = "2"
portable-atomic = { version = "1.13", features = ["critical-section"] }
log = "0.4"
pio-proc = "0.3"
pio = "0.3.0"
rand = { version = "0.9.2", default-features = false }
[profile.release]
debug = 2
# Below configs are here to mute the rust-analyzer error.
# "Can't find crate for 'test'" as this is a no_std project
[[bin]]
name = "pico-w-remote-temp-logger"
test = false
bench = false

36
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");
}

17
memory.x Normal file
View File

@@ -0,0 +1,17 @@
MEMORY {
BOOT2 : ORIGIN = 0x10000000, LENGTH = 0x100
FLASH : ORIGIN = 0x10000100, LENGTH = 2048K - 0x100
/* Pick one of the two options for RAM layout */
/* OPTION A: Use all RAM banks as one big block */
/* Reasonable, unless you are doing something */
/* really particular with DMA or other concurrent */
/* access that would benefit from striping */
RAM : ORIGIN = 0x20000000, LENGTH = 264K
/* OPTION B: Keep the unstriped sections separate */
/* RAM: ORIGIN = 0x20000000, LENGTH = 256K */
/* SCRATCH_A: ORIGIN = 0x20040000, LENGTH = 4K */
/* SCRATCH_B: ORIGIN = 0x20041000, LENGTH = 4K */
}

193
src/main.rs Normal file
View File

@@ -0,0 +1,193 @@
//! This example uses the RP Pico W board Wifi chip (cyw43).
//! Connects to specified Wifi network and creates a TCP endpoint on port 1234.
#![no_std]
#![no_main]
#![allow(async_fn_in_trait)]
use core::str::from_utf8;
use cyw43::{JoinOptions, aligned_bytes};
use cyw43_pio::{DEFAULT_CLOCK_DIVIDER, PioSpi};
use defmt::*;
use embassy_executor::Spawner;
use embassy_net::tcp::TcpSocket;
use embassy_net::{Config, StackResources};
use embassy_rp::adc::{Adc, Channel, Config as AdcConfig, InterruptHandler as AdcIntHandler};
use embassy_rp::clocks::RoscRng;
use embassy_rp::gpio::{Level, Output, Pull};
use embassy_rp::peripherals::{DMA_CH0, PIO0};
use embassy_rp::pio::{InterruptHandler, Pio};
use embassy_rp::{bind_interrupts, dma};
use embassy_time::Duration;
use embedded_io_async::Write;
use static_cell::StaticCell;
use {defmt_rtt as _, panic_probe as _};
bind_interrupts!(struct Irqs {
PIO0_IRQ_0 => InterruptHandler<PIO0>;
DMA_IRQ_0 => dma::InterruptHandler<DMA_CH0>;
ADC_IRQ_FIFO => AdcIntHandler;
});
const WIFI_NETWORK: &str = "PenetanguIoT"; // change to your network SSID
const WIFI_PASSWORD: &str = "waterstiot"; // change to your network password
#[embassy_executor::task]
async fn cyw43_task(
runner: cyw43::Runner<'static, cyw43::SpiBus<Output<'static>, PioSpi<'static, PIO0, 0>>>,
) -> ! {
runner.run().await
}
#[embassy_executor::task]
async fn net_task(mut runner: embassy_net::Runner<'static, cyw43::NetDriver<'static>>) -> ! {
runner.run().await
}
#[embassy_executor::main]
async fn main(spawner: Spawner) {
info!("Hello World!");
let p = embassy_rp::init(Default::default());
let mut rng = RoscRng;
let fw = aligned_bytes!("../../embassy/cyw43-firmware/43439A0.bin");
let clm = aligned_bytes!("../../embassy/cyw43-firmware/43439A0_clm.bin");
let nvram = aligned_bytes!("../../embassy/cyw43-firmware/nvram_rp2040.bin");
// To make flashing faster for development, you may want to flash the firmwares independently
// at hardcoded addresses, instead of baking them into the program with `include_bytes!`:
// probe-rs download 43439A0.bin --binary-format bin --chip RP2040 --base-address 0x10100000
// probe-rs download 43439A0_clm.bin --binary-format bin --chip RP2040 --base-address 0x10140000
//let fw = unsafe { core::slice::from_raw_parts(0x10100000 as *const u8, 230321) };
//let clm = unsafe { core::slice::from_raw_parts(0x10140000 as *const u8, 4752) };
let pwr = Output::new(p.PIN_23, Level::Low);
let cs = Output::new(p.PIN_25, Level::High);
let mut pio = Pio::new(p.PIO0, Irqs);
let spi = PioSpi::new(
&mut pio.common,
pio.sm0,
DEFAULT_CLOCK_DIVIDER,
pio.irq0,
cs,
p.PIN_24,
p.PIN_29,
dma::Channel::new(p.DMA_CH0, Irqs),
);
static STATE: StaticCell<cyw43::State> = StaticCell::new();
let state = STATE.init(cyw43::State::new());
let (net_device, mut control, runner) = cyw43::new(state, pwr, spi, fw, nvram).await;
spawner.spawn(unwrap!(cyw43_task(runner)));
control.init(clm).await;
control
.set_power_management(cyw43::PowerManagementMode::PowerSave)
.await;
let config = Config::dhcpv4(Default::default());
//let config = embassy_net::Config::ipv4_static(embassy_net::StaticConfigV4 {
// address: Ipv4Cidr::new(Ipv4Address::new(192, 168, 69, 2), 24),
// dns_servers: Vec::new(),
// gateway: Some(Ipv4Address::new(192, 168, 69, 1)),
//});
// Generate random seed
let seed = rng.next_u64();
// Init network stack
static RESOURCES: StaticCell<StackResources<3>> = StaticCell::new();
let (stack, runner) = embassy_net::new(
net_device,
config,
RESOURCES.init(StackResources::new()),
seed,
);
spawner.spawn(unwrap!(net_task(runner)));
while let Err(err) = control
.join(WIFI_NETWORK, JoinOptions::new(WIFI_PASSWORD.as_bytes()))
.await
{
info!("join failed: {:?}", err);
}
info!("waiting for link...");
stack.wait_link_up().await;
info!("waiting for DHCP...");
stack.wait_config_up().await;
// And now we can use it!
info!("Stack is up!");
let mut rx_buffer = [0; 4096];
let mut tx_buffer = [0; 4096];
let mut buf = [0; 4096];
let mut adc = Adc::new(p.ADC, Irqs, AdcConfig::default());
let mut adc_chans = [
Channel::new_temp_sensor(p.ADC_TEMP_SENSOR),
Channel::new_pin(p.PIN_26, Pull::None),
Channel::new_pin(p.PIN_27, Pull::None),
Channel::new_pin(p.PIN_28, Pull::None),
];
loop {
let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer);
socket.set_timeout(Some(Duration::from_secs(10)));
control.gpio_set(0, false).await;
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());
control.gpio_set(0, true).await;
loop {
let n = match socket.read(&mut buf).await {
Ok(0) => {
warn!("read EOF");
break;
}
Ok(n) => n,
Err(e) => {
warn!("read error: {:?}", e);
break;
}
};
info!("rxd {}", from_utf8(&buf[..n]).unwrap());
// read all the adcs and respond
let mut i = 0usize;
for ch in adc_chans.iter_mut() {
let lvl = adc.read(ch).await.unwrap();
let bytes = lvl.to_le_bytes();
for v in bytes.iter() {
buf[i] = *v;
i += 1;
}
}
buf[i] = b'E';
match socket.write_all(&buf[..n]).await {
Err(e) => {
warn!("write error: {:?}", e);
break;
}
_ => (),
};
}
}
}